我应得的少数编程任务之一是与位级运算符打交道,我希望我能正确地做到这一点。
#include <stdio.h>
int main(void){
int x;
printf("Enter an x: ");
scanf("%x", &x);
printf("X = %d\n", x);
// Any bit in x is 1
x && printf("A bit in x is 1!\n");
// Any bit in x is 0
~x && printf("A bit in x is 0!\n");
// Least significant byte of x has a bit of 1
(x & 0xFF) && printf("A bit in least significant byte of x is 1!\n");
// Most significant byte of x has a bit of 0
int most = (x & ~(0xFF<<(sizeof(int)-1<<3)));
most && printf("A bit in the most significant byte of x is 0!\n");
return 0;
}
赋值限制了我们可以使用的内容,因此可能没有循环或条件以及许多其他限制。我对位级运算符有些困惑,所以我只是希望是否有任何错误可以解决,并了解错误原因。谢谢。
您不应将带符号的整数用于这些操作,因为在某些情况下会导致未定义的/实现定义的行为:带符号的整数的算术移位
int most = (x & ~(0xFF<<(sizeof(int)-1<<3)));
您应该否定x
,而不是右侧:
int most = (~x & (0xFF<<(sizeof(int)-1<<3)));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句