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

前端 未结 2 1586
-上瘾入骨i
-上瘾入骨i 2020-12-20 15:28

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 de

相关标签:
2条回答
  • 2020-12-20 15:40

    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.

    0 讨论(0)
  • 2020-12-20 15:45

    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.

    0 讨论(0)
提交回复
热议问题