我应付的少数编程任务之一是处理位级操作符,我希望我能正确地做到这一点。
#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;
}
该分配限制了我们可以使用的内容,因此可能没有循环或条件以及许多其他限制。我对位级操作符有点困惑所以我只是希望如果有任何错误我可以修复它并了解它为什么是错误的。感谢。
答案 0 :(得分:2)
您不应该对这些操作使用有符号整数,因为某些情况会导致未定义/实现定义的行为:Arithmetic bit-shift on a signed integer
int most = (x & ~(0xFF<<(sizeof(int)-1<<3)));
你应该否定x
,而不是右手:
int most = (~x & (0xFF<<(sizeof(int)-1<<3)));