// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; namespace E { public class PowFun { public static bool IsPowerOf2_v1(int num) { int j = 1; for (int i = 0; i < 31; i++) { if(num == j) return true; j <<= 1; } return false; } private static readonly int[] pow2 = { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824 }; public static bool IsPowerOf2_v2(int num) { for (int i = 0; i < 31; i++) { if(num == pow2[i]) return true; } return false; } private static int BitCount(uint num) { uint tmp; tmp = num - ((num >> 1) & 3681400539U) - ((num >> 2) & 1227133513U); return (int)((tmp + (tmp >> 3)) & 3340530119U) % 63; } public static bool IsPowerOf2_v3(int num) { return BitCount((uint)num) == 1; } private static readonly int[] bits8 = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 }; public static bool IsPowerOf2_v4(int num) { int tmp = num; int sum = bits8[tmp & 0xFF]; if(sum > 1) return false; tmp >>= 8; sum += bits8[tmp & 0xFF]; if(sum > 1) return false; tmp >>= 8; sum += bits8[tmp & 0xFF]; if(sum > 1) return false; tmp >>= 8; sum += bits8[tmp & 0xFF]; return sum == 1; } private static int[] bit16; static PowFun() { bit16 = new int[65536]; for(int i = 0; i < bit16.Length; i++) { bit16[i] = BitCount((uint)i); } } public static bool IsPowerOf2_v5(int num) { int tmp = num; int sum = bit16[tmp & 0xFFFF]; if(sum > 1) return false; tmp >>= 16; sum += bit16[tmp & 0xFFFF]; return sum == 1; } public static bool IsPowerOf2_v6(int num) { return num > 0 && (num & (num - 1)) == 0; } private delegate bool Check(int num); private static void Test(Check p) { DateTime dt1 = DateTime.Now; int n = 0; for(int i = 0; i < int.MaxValue/10; i++) { if(p(i)) n++; } DateTime dt2 = DateTime.Now; Console.WriteLine((dt2 - dt1).TotalSeconds + " secs (" + n + ")"); } public static void Main(string[] args) { Test(IsPowerOf2_v1); Test(IsPowerOf2_v2); Test(IsPowerOf2_v3); Test(IsPowerOf2_v4); Test(IsPowerOf2_v5); Test(IsPowerOf2_v6); } } }