我不明白为什么下面代码中最后的 printf
没有打印 255。
char c;
c = c & 0;
printf("The value of c is %d", (int)c);
int j = 255;
c = (c | j);
printf("The value of c is %d", (int)c);
最佳答案
在大多数实现中,char
类型是有符号的,因此它的范围从 -128
到 127
。
这意味着,11111111
(用二进制表示的255
)等于-1
。 (因为它表示为存储在 two's complement 中的值)
要获得您期望的结果,您需要将 c
声明为 unsigned char
,如下所示:
unsigned char c = 0;
int j = 255;
c = (c | j);
printf("The value of c is %d", (int)c);
关于c - C 中的 OR 运算符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7214835/