创建某些位掩码的步骤?

时间:2015-10-11 23:52:07

标签: c bit-manipulation bitmask

我正在寻找一种使用移位和按位运算符创建位掩码的一般方法,并警惕左移的溢出

离。 0x80000000类似于(~0>> 31)<<如果我错了,请纠正我

更具体地说,0xAAAAAAAA和0x55555555是我挣扎的

1 个答案:

答案 0 :(得分:0)

printf("0x%08x\n",  (~0 << 31));
unsigned int x;
x = (~0 << 31);
x >>= 31;
x |= x << 2;
x |= x << 4;
x |= x << 8;
x |= x << 16;
printf("0x%08X\n",  x);
x = (~0 << 31);
x >>= 30;
x |= x << 2;
x |= x << 4;
x |= x << 8;
x |= x << 16;
printf("0x%08X\n",  x);

http://ideone.com/N3Yx8Z

结果

0x80000000
0x55555555
0xAAAAAAAA