有没有一种简单的方法将单个数字的所有位异或在一起,即 C 中的一元异或?
具有以下效果的东西:
result = ^(0x45); // ( 0 ^ 1 ^ 0 ^ 0 ^ 0 ^ 1 ^ 0 ^ 1 = 1)
result = ^(0x33); // ( 0 ^ 0 ^ 1 ^ 1 ^ 0 ^ 0 ^ 1 ^ 1 = 0)
GCC 为此内置了一个:
int xor_bits(unsigned x) {
return __builtin_parity(x);
}
或者,您可以通过计算设置位的数量来计算奇偶校验。内置的 gcc 是__builtin_popcount()
:
int xor_bits(unsigned x) {
return __builtin_popcount(x) & 1;
}
如果你只想坚持标准 C,https://graphics.stanford.edu/~seander/bithacks.html https://graphics.stanford.edu/~seander/bithacks.html and 如何计算 32 位整数中设置的位数? https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer有一些很好的解决方案来计算设置位的数量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)