[英]C - Using bitwise operators to determine if all even bits are set to 1
Hi I am having trouble getting this function to work. 嗨,我在让此功能正常工作时遇到了麻烦。 Basically, the the function should return a 1 if all even place bits are 1 and 0 otherwise.
基本上,如果所有偶数位均为1,则函数应返回1,否则返回0。 This program always prints 0 for some reason.
由于某种原因,该程序始终打印0。
Here is the code : 这是代码:
#include <stdio.h>
int allEvenBits(int);
int main() {
printf("%d\n", allEvenBits(0xFFFFFFFE));
return 0;
}
int allEvenBits(int X) {
return !((X & 0x55555555) ^ 0x55555555);
}
You are checking the odd bits for the even should be with 0xAAAAAAAA
: 您正在检查偶数的奇数位应为
0xAAAAAAAA
:
const unsigned int ODD_BITS_SET = 0x55555555;
const unsigned int EVEN_BITS_SET = 0xAAAAAAAA;
unsigned int allOddBits(unsigned int X) { return (X & ODD_BITS_SET) == ODD_BITS_SET; }
unsigned int allEvenBits(unsigned int X) { return (X & EVEN_BITS_SET) == EVEN_BITS_SET; }
Better to give a name to the magic number. 最好给魔术数字起个名字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.