bitParity - 查找整数中的奇数位
我必须创建一个函数 bitParity(int x)
,它接受一个整数,如果中有奇数个 0
则返回 1
位形式为x
,否则为0
。
例如: bitParity(5) = 0, bitParity(7) = 1
但是,这很困难,因为我只能在这个问题上使用位运算符 (! ∼ & ˆ | +
<>>
是唯一合法的)。这意味着,没有循环、if-then
或任何类似的东西。可以使用常量。
到目前为止,我所拥有的不起作用,但我认为我应该移动整数 16
、8
和 4
的位次并对剩余整数进行异或运算。
有人可以提供一些建议吗?谢谢。
I have to create a function bitParity(int x)
that takes an integer and returns 1
if there is an odd number of 0
's in the bit form of x
, and 0
otherwise.
Ex: bitParity(5) = 0, bitParity(7) = 1
However, this is difficult as I can only use bit operators on this problem (! ˜ & ˆ | + << >>
are the only legal ones). That means, no loops, if-then
, or anything of the sort. Constants can be used.
So far, what I have doesn't work, but I figured that I should shift the bits of the integer 16
, 8
, and 4
times and XOR
the remaining integers.
Can anyone offer some advice? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于 32 位数字:
注意* 0x6996 表示数字 1、2、4、7、8、11、13 和 14 的位向量。所有 4 位值都可以表示为奇数位数。在 0x6996 中,如果某个位在向量中的位置对应于 (1、2、4、7、8、11、13 或 14),则该位被设置。
这就是为什么 (0x6996 >> x) & 1 有意义,在移位 x 后,如果 x 等于位向量中的任何值,则该表达式只会返回 1,这意味着设置了奇数个位。
For 32bit numbers:
Note* 0x6996 represents a bit vector of the numbers 1, 2, 4, 7, 8, 11, 13, and 14. All of the 4-bit values that can be represented by an odd number of bits. In 0x6996, a bit is set if its position in the vector corresponds with (1, 2, 4, 7, 8, 11, 13, or 14).
This is why (0x6996 >> x) & 1 makes sense, after the shift by x, this expression will only result in a returned 1 if x is equal to any of the values in the bit vector, meaning an odd number of bits were set.
这可以通过循环正确解决。但这里有一种方法可以做到这一点。
编辑:我不需要 &。更好的版本:
This is properly solved with a loop. But here is a way to do it without.
Edit: I don't need the &. A better version:
这是我在学士论文工作期间使用的函数之一;)
因此 4B 整数的总计数将是:
奇偶校验:
我一直想重用这些代码:)
编辑:
您可能会注意到
unsigned char
(8b) 可以分为 2 部分,每部分 4b 长,这意味着 16 个值易于存储和重用。所以你从整数中取出第一个 8b,将它们分成两部分。确保它们都在<0,15>
区间内,直接获取位数即可。重复 :)Here's one of my functions that I used during my work on bachelor thesis ;)
So total count for 4B integer would be:
And parity:
I always wanted to reuse those codes :)
EDIT:
As you may noticed
unsigned char
(8b) can be split into 2 pieces each 4b long, that means 16 values which are easy to store and reuse. So you take first 8b from integer, split them into two pieces. Make sure them are both in interval<0,15>
, and just directly get bit count. Repeat :)