bitParity - 寻找一个整数奇数位 [英] bitParity - Finding odd number of bits in an integer

查看:332
本文介绍了bitParity - 寻找一个整数奇数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建一个函数 bitParity(INT X),它接受一个整数,并返回 1 如果有奇数 0 的在 X 0 其他。

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.

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

然而,这是困难的,因为我只能在这个问题上(〜&放大器使用位运算符; |!+<<>> 是唯一法律的)。这意味着,没有循环,的if-then ,或诸如此类的事。常量可以被使用。

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.

到目前为止,我有什么不工作,但我想,我应该在整数位移 16 8 4 时间和 XOR 剩余的整数。

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.

推荐答案

这是正确的一个循环解决。但这里是一个办法做到这一点没有。

This is properly solved with a loop. But here is a way to do it without.

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)

编辑:我不需要和放大器;.一个更好的版本:

I don't need the &. A better version:

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

这篇关于bitParity - 寻找一个整数奇数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆