技巧1:检查整数是奇数还是偶数
if ((x & 1) == 0)
{
// x is even
}
else
{
// x is odd
}
技巧2:测试第n位比特
if (x & (1<<n))
{
// n-th bit is set
}
else
{
// n-th bit is not set
}
技巧3:将第n位设为1
y = x | (1<<n)
技巧4:将第n位设为0
y = x & ~(1<<n)
技巧5:将第n位取反
y = x ^ (1<<n)
技巧6:将最右边的数值为1的bit位设为0
y = x & (x-1)
技巧7:隔离最右边值为1的比特位
y = x & (-x)
技巧8:右传播最右边值为1的比特位
y = x | (x-1)
技巧9:隔离最右边值为0的比特位
y = ~x & (x+1)
技巧10:将最右边值为0的比特取反
y = x | (x+1)
本文转自:https://www.cnblogs.com/programnote/p/4686330.html