bitParity – 查找整数中的奇数位数

我必须创建一个函数bitParity(int x) ,它取一个整数,如果x的位forms有一个奇数0 ,则返回1否则返回0

例如: bitParity(5) = 0, bitParity(7) = 1

但是,这很难,因为我只能在这个问题上使用位运算符( ! ˜ & ˆ | + <>是唯一合法的)。 这意味着,没有循环, if-then或任何类型的东西。 可以使用常量。

到目前为止,我所做的并不起作用,但我认为我应该将整数的位移16,8和4倍,并将剩余的整数进行XOR

有人可以提供一些建议吗? 谢谢。

这可以通过循环正确解决。 但是这是一种没有它的方法。

 x = (x & 0x0000FFFF) ^ (x >> 16) x = (x & 0x000000FF) ^ (x >> 8) x = (x & 0x0000000F) ^ (x >> 4) x = (x & 0x00000003) ^ (x >> 2) x = (x & 0x00000001) ^ (x >> 1) 

编辑:我不需要&。 更好的版本:

 x ^= x >> 16 x ^= x >> 8 x ^= x >> 4 x ^= x >> 2 x ^= x >> 1 x &= 1; 

对于32位数字:

 function bitParity(int x) { x ^= x >> 16; x ^= x >> 8; x ^= x >> 4; x &= 0xf; return (0x6996 >> x) & 1; } 

这是我在学士论文工作中使用的一个function;)

 /** Calculates number of bits in unsigned char * @brief Bit count * @param input to be checked * @return int 0-8 */ int bitCount( unsigned char input) { static unsigned char count[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; return (int)( count[ input & 0x0f] + count[ (input >> 4) & 0x0f] ); } 

所以4B整数的总数将是:

 int bytes = bitCount( (unsigned char)((number >> 0)&255)) + bitCount( (unsigned char)((number >> 8)&255)) + bitCount( (unsigned char)((number >> 16)&255)) + bitCount( (unsigned char)((number >> 24)&255)); 

和平价:

  return bytes%2; return bytes&1; // if you preffer 

我一直想重用那些代码:)

编辑 :你可能会注意到unsigned char (8b)可以分成2个,每个4b长,这意味着16个值易于存储和重用。 所以你从整数中取出第一个8b,将它们分成两部分。 确保它们都在区间<0,15> ,并且直接得到位数。 重复:)

这是我的答案:

 int bitParity(unsigned x) { unsigned flag = 0; while (x != 0) { flag ^= (x & 1); x >>= 1; } return flag; } 

编辑:这是错的,抱歉,我没有注意到“没有循环,if-then,或类似的任何东西。”