常用位操作的c++实现
Posted 周旭光
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了常用位操作的c++实现相关的知识,希望对你有一定的参考价值。
看到这个标题,可能大家会误解,其实就是贡献几个比较实用的运用位运算实现的操作,这对于加快程序的运行速度很有帮助。具体的实现是参考http://graphics.stanford.edu/~seander/bithacks.html实现的。
下面给出其函数声明及其实现。
//判断该整数是否是2的整数次方
bool IsPowerOfTwo (unsigned int value);
bool IsPowerOfTwo (int value);
//求以2为底的结果
unsigned int Log2OfPowerOfTwo (unsigned int powerOfTwo);
int Log2OfPowerOfTwo (int powerOfTwo);
//判断两个数是否异号
bool IsOppositeSigns(int value1,int value2);
//不使用分支计算绝对值
unsigned int GetAbs(int value);
//大于等于value的最近的二的次方的数
unsigned int NextPowerOfTwo(unsigned int value);
//实现
bool IsPowerOfTwo (unsigned int value)
return (value > 0) && ((value & (value - 1)) == 0);
bool IsPowerOfTwo (int value)
return (value > 0) && ((value & (value - 1)) == 0);
unsigned int Log2OfPowerOfTwo (unsigned int powerOfTwo)
unsigned int log2 = (powerOfTwo & 0xAAAAAAAA) != 0;
log2 |= ((powerOfTwo & 0xFFFF0000) != 0) << 4;
log2 |= ((powerOfTwo & 0xFF00FF00) != 0) << 3;
log2 |= ((powerOfTwo & 0xF0F0F0F0) != 0) << 2;
log2 |= ((powerOfTwo & 0xCCCCCCCC) != 0) << 1;
return log2;
int Log2OfPowerOfTwo (int powerOfTwo)
unsigned int log2 = (powerOfTwo & 0xAAAAAAAA) != 0;
log2 |= ((powerOfTwo & 0xFFFF0000) != 0) << 4;
log2 |= ((powerOfTwo & 0xFF00FF00) != 0) << 3;
log2 |= ((powerOfTwo & 0xF0F0F0F0) != 0) << 2;
log2 |= ((powerOfTwo & 0xCCCCCCCC) != 0) << 1;
return (int)log2;
bool IsOppositeSigns(int value1,int value2)
return (value1 ^ value2) < 0;
unsigned int GetAbs(int value)
unsigned int r; // the result goes here
int const mask = value >> (sizeof(int) * CHAR_BIT - 1);
//r = (value + mask) ^ mask;
//Patented variation:
r = (value ^ mask) - mask;
return r;
unsigned int NextPowerOfTwo(unsigned int value)
value--;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
value++;
return value;
希望对大家有用
以上是关于常用位操作的c++实现的主要内容,如果未能解决你的问题,请参考以下文章