看到这个标题,可能大家会误解,其实就是贡献几个比较实用的运用位运算实现的操作,这对于加快程序的运行速度很有帮助。具体的实现是参考
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;
}
希望对大家有用
版权声明:本文为zhouxuguang236原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。