与C〜运算符(按位非)混淆并比较char变量 [英] Confusion with C ~ operator (bitwise Not) and comparing char variables
问题描述
我希望使用普通C"比较两个8位字节,以确定第二个是否是第一个的按位补码.例如,如果Byte1是二进制00001111(十进制为15),我想测试Byte2是否是二进制11110000(十进制为240).我希望使用无符号字符来表示字节,使用C按位NOT运算符〜"和简单的if(==)测试来完成此操作.
Using "ordinary C", I wish to compare two 8 bit bytes to determine if the second is the bitwise complement of the first. For example if Byte1 is binary 00001111 (15 in decimal) I want to test whether or not Byte2 is binary 11110000 (240 in decimal). I expected to do this using unsigned chars to represent the bytes, the C bitwise NOT operator "~" and a simple if( == ) test.
谁能为我解释以下代码为何不起作用(即,我希望它输出"True",但实际上输出"False").
Can anyone explain for me why the following code doesn't work (ie. I expect it to output "True" but it actually outputs "False").
unsigned char X = 15;
unsigned char Y = 240;
if( Y == ~X)
printf("True");
else
printf("False");
我想我可以对字节进行XOR,然后测试255,但是上面的if(==)比较为什么不起作用?
I guess I could XOR the bytes together then test for 255, but why doesn't the above if( == ) comparison work ?
谢谢
马丁.
推荐答案
因为积分提升导致右侧的数学运算为int
.如果将结果分配回给char
(如unsigned char Z = ~X
),则这些高位将再次被截断并Y == Z
.
Because integral promotion causes the math on the right side to be done as int
. If you assigned the result back to a char
like unsigned char Z = ~X
those upper bits would be truncated off again and Y == Z
.
这篇关于与C〜运算符(按位非)混淆并比较char变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!