我正在使用一个函数,但遇到了一些麻烦。我们只能使用位运算符(这意味着不能使用逻辑运算符、循环或if语句),且不允许使用大于0xFF的常量。
我已经让函数正常工作了,但它使用了一个巨大的常量。当我尝试使用较小的数字和移位来实现它时,我无法让它正常工作,也不确定原因在哪里。
该函数应检查给定整数中的所有偶数位,并在它们都设置为1时返回1。
有效代码
我在这里做错了什么吗?
我已经让函数正常工作了,但它使用了一个巨大的常量。当我尝试使用较小的数字和移位来实现它时,我无法让它正常工作,也不确定原因在哪里。
该函数应检查给定整数中的所有偶数位,并在它们都设置为1时返回1。
有效代码
int allEvenBits(int x) {
/* implements a check for all even-numbered bits in the word set to 1 */
/* if yes, the program outputs 1 WORKING */
int all_even_bits = 0x55555555;
return (!((x & all_even_bits) ^ all_even_bits));
}
尝试使用较小的常数和移位进行实现
int allEvenBits(int x) {
/* implements a check for all even-numbered bits in the word set to 1 */
/* if yes, the program outputs 1 WORKING */
int a, b, c, d, e = 0;
int mask = 0x55;
/* first 8 bits */
a = (x & mask)&1;
/* second eight bits */
b = ((x>>8) & mask)&1;
/* third eight bits */
c = ((x>>16) & mask)&1;
/* fourth eight bits */
d = ((x>>24) & mask)&1;
e = a & b & c & d;
return e;
}
我在这里做错了什么吗?