00001 #ifndef BINARYMATH_H
00002 #define BINARYMATH_H
00003
00004
00005
00006 inline unsigned int modulusPow2( unsigned int divident, unsigned int powerOf2Divisor)
00007 {
00008 return divident & (powerOf2Divisor - 1);
00009 }
00010
00011 inline unsigned int pow2( unsigned int i)
00012 {
00013 return 1 << i;
00014 }
00015
00016 inline unsigned int nextPowerOf2( unsigned int val)
00017 {
00018 val--;
00019 val = (val >> 1) | val;
00020 val = (val >> 2) | val;
00021 val = (val >> 4) | val;
00022 val = (val >> 8) | val;
00023 val = (val >> 16) | val;
00024 val++;
00025 return val;
00026 }
00027
00028 inline unsigned int maxpow2divisor( unsigned int i)
00029 {
00030 unsigned int mask = 1;
00031 while( (i & mask) == 0)
00032 {
00033 mask <<= 1;
00034 }
00035 return mask;
00036 }
00037
00038 inline unsigned int trailing_zeros2( unsigned int i)
00039 {
00040 unsigned int b = i & (~i+1);
00041 b--;
00042 b = (b & 0x55555555) + ((b>>1) & 0x55555555);
00043 b = (b & 0x33333333) + ((b>>2) & 0x33333333);
00044 b = (b & 0x0f0f0f0f) + ((b>>4) & 0x0f0f0f0f);
00045 b = (b & 0x00ff00ff) + ((b>>8) & 0x00ff00ff);
00046 b = (b & 0x0000ffff) + ((b>>16) & 0x0000ffff);
00047 return b;
00048 }
00049
00050
00051 inline int trailing_zeros(unsigned x){
00052 int n;
00053 if (x == 0) return(32);
00054 n = 1;
00055 if ((x & 0x0000FFFF) == 0) {n = n +16; x = x >>16;}
00056 if ((x & 0x000000FF) == 0) {n = n + 8; x = x >> 8;}
00057 if ((x & 0x0000000F) == 0) {n = n + 4; x = x >> 4;}
00058 if ((x & 0x00000003) == 0) {n = n + 2; x = x >> 2;}
00059 return n - (x & 1);
00060 }
00061
00062 inline int floorLog2(unsigned int n) {
00063 unsigned int pos = 0;
00064 if (n >= 1<<16) { n >>= 16; pos += 16; }
00065 if (n >= 1<< 8) { n >>= 8; pos += 8; }
00066 if (n >= 1<< 4) { n >>= 4; pos += 4; }
00067 if (n >= 1<< 2) { n >>= 2; pos += 2; }
00068 if (n >= 1<< 1) { pos += 1; }
00069 return ((n == 0) ? (-1) : pos);
00070 }
00071
00072 inline int ceilLog2(unsigned int n) {
00073 unsigned int pos = 0;
00074 if (n >= 1<<16) { n >>= 16; pos += 16; }
00075 if (n >= 1<< 8) { n >>= 8; pos += 8; }
00076 if (n >= 1<< 4) { n >>= 4; pos += 4; }
00077 if (n >= 1<< 2) { n >>= 2; pos += 2; }
00078 if (n >= 1<< 1) { pos += 1; }
00079 return ((n == 0) ? (-1) : (pos + 1));
00080 }
00081
00082 inline int isPowerOf2 (unsigned int x)
00083 {
00084 while (((x & 1) == 0) && x > 1)
00085 x >>= 1;
00086 return (x == 1);
00087 }
00088
00089
00090 #endif //BINARYMATH_H