为什么带有 XOR 的翻转所有位会像 OR 一样打印?
这里我尝试实现 XOR (^) 来翻转数字中的所有位。但由于某种原因,它打印出全 1,就好像 XOR (^) 实际上是 OR (|)。我似乎无法理解为什么。我查看了运算符优先级,但我不知道这会如何真正产生影响。
#include <stdio.h>
#include <stdlib.h>
void flipallbits(int x) {
int i;
for( i = 31; i >= 0; i--) {
if( x ^ 1 << i ) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
int main() {
int num = 6541;
flipallbits(num);
}
Here I am trying to implement the XOR (^) to flip all the bits in the number. But for some reason, it prints out all 1's as if the XOR (^) was in fact an OR (|). I can't seem to understand why. I took a look at operator precedence but I don't see how that would really make a difference here.
#include <stdio.h>
#include <stdlib.h>
void flipallbits(int x) {
int i;
for( i = 31; i >= 0; i--) {
if( x ^ 1 << i ) {
printf("1");
} else {
printf("0");
}
}
printf("\n");
}
int main() {
int num = 6541;
flipallbits(num);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
x ^ 1 << i
与x ^ (1 << i)
相同。因此,在循环的每次迭代中,您都会翻转不同的位。但您的测试只是检查结果是否非零;这始终是正确的,因为您的输入值设置了多个位。目前尚不清楚您想要实现什么目标。如果您只想依次打印所有位,则需要
x & 1<<;我。
x ^ 1 << i
is the same asx ^ (1 << i)
. So on each iteration of your loop, you're flipping a different bit. But your test is simply checking that the result is non-zero; this is always true, because your input value has more than one bit set.It's not clear what you're trying to achieve. If you simply want to print all the bits in turn, you want
x & 1 << i
.