Search code examples
cbinarybitbitmask

How does ~0x00 return -1?


As far as I know, ~0x00 equals to: First step, change 0's to 1 and 1's to zero, Second step, add 1 Step 1: 11111111111111111111111111111 (count =32)

Step 2: 11111111111111111111111111111+1=0

Where am I doing wrong?


Solution

  • The ~ operator does not perform 2's complement negation. You can do that with the unary - operator (assuming your machine uses 2's complement representation).

    What ~ does is invert all bits. That's all it does, no adding 1.