Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion with C ~ operator (bitwise Not) and comparing char variables

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.

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");

I guess I could XOR the bytes together then test for 255, but why doesn't the above if( == ) comparison work ?

Thanks,

Martin.

like image 676
Martin Irvine Avatar asked Oct 29 '11 18:10

Martin Irvine


2 Answers

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.

like image 131
Ben Jackson Avatar answered Sep 17 '22 23:09

Ben Jackson


The ~ operator causes its operands to be promoted to int before being complemented. ~15 is not 240 but some other value, depending on the size of int.

Just use if (X + Y == 255) and it should work.

like image 5
Jens Avatar answered Sep 18 '22 23:09

Jens