奇数位的位奇偶校验码
我正在尝试查找位串的奇偶校验,以便如果 x 有奇数个 0,则返回 1。
我只能使用基本的按位运算,到目前为止我已经通过了大多数测试,但我想知道两件事:
为什么 x ^ (x + ~1) 有效?我偶然发现了这一点,但如果位数为奇数,它似乎给你 1,如果位数为偶数,它似乎给你 1。就像 7^6 = 1 因为 7 = 0b0111
这是解决问题的正确方向吗?我假设我的问题源于第一个操作,特别是 (x + ~1) 因为它会溢出某些 2 的补数。谢谢
码:
int bitParity(int x) {
int first = x ^ (x + ~1);
int second = first ^ 1; // if first XOR gave 1 you'll return 0 here
int result = !!second;
return result;
}
I am trying to find the parity of a bitstring so that it returns 1 if x has an odd # of 0's.
I can only use basic bitwise operations and what I have so far passes most of the tests, but I'm wondering 2 things:
Why does x ^ (x + ~1) work? I stumbled upon this, but it seems to give you 1 if there are an odd number of bits and something else if even. Like 7^6 = 1 because 7 = 0b0111
Is this the right direction of problem solving for this? I'm assuming my problem is stemming from the first operation, specifically (x + ~1) because it would overflow certain 2's complement numbers. Thanks
Code:
int bitParity(int x) {
int first = x ^ (x + ~1);
int second = first ^ 1; // if first XOR gave 1 you'll return 0 here
int result = !!second;
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
据我所知,你的奇偶校验函数实际上并不起作用 - 它似乎在大约一半的时间里得到了正确的答案,这与返回随机结果一样好(甚至只是始终返回 0 或 1) 。
有几种位级黑客确实有效:http ://graphics.stanford.edu/~seander/bithacks.html#ParityNaive - 您可能想看看其中的最后一个:http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel
Your parity function doesn't actually work as far as I can tell - it seems to get the answer right about half of the time, which is about as good as returning a random result (or even just returning 0 or 1 all the time).
There are several bit level hacks which do actually work at: http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive - you probably want to look at the last one of these: http://graphics.stanford.edu/~seander/bithacks.html#ParityParallel
我会使用实际计数,而不是利用数字表示的位级黑客,这样既感觉更安全,也更干净且易于理解。当然,可能会慢一些,但这是一个相当不错的权衡,尤其是当人们对性能预期一无所知时。
为此,只需编写代码来计算 1 位的数量,最直接的解决方案通常归结为循环。
更新:鉴于(奇怪且烦人的)限制,我的回应可能是unwind "naive" 解决方案中给出的循环 <一个href="http://graphics.stanford.edu/~seander/bithacks.html" rel="nofollow">bithacks 页面。那不太好,但我可以去做一些有用的事情。 :)
I would use actual counting rather than bit-level hacks that exploit the representation of the numbers, that would both feel safer and be more clean and easy to understand. Probably slower, of course, but that's a quite nice trade-off especially when one doesn't know anything about the performance expectations.
Do to this, just write code to count the number of 1 bits, the most straight-forward solution generally boils down to a loop.
UPDATE: Given the (weird and annoying) limitations, my response would probably be to unwind the loop given in the "naive" solution on the bithacks page. That wouldn't be pretty, but then I could go do something useful. :)
位奇偶校验可以这样完成:
Bit parity may be done like this: