Bit Flipping – How Does Complementing Work?

bitwise-operators

I am currently learning about bitwise operation, so bear with me. I understand AND, OR, and shifting. What I don't understand is bit flipping.

So, 5 is 0101. When someone says to me "flip those", it would result in 1010 which is 10. So why does ~5result in -6?

I think I got this very wrong. Can someone enlight me?

(I am putting this here because I think it is a general programming question and not a specific one, which would belong to stack overflow).

Edit 1 Thanks to mcfinnigan's comment I learned that there is a "most significant bit" that defines if a number is positive or negative (correct me if I'm wrong). This would explain why positive results are ending up negative and vice versa. However, IMO the example above would result in -10 then.

Edit 2 Thanks to Don 01001100 and S.Lott, I finally got it.

Best Answer

If you're using a two's complement signed integer, then the first bit indicates the sign, and the remaining bits count down from -1, with -1 represented as all "1" bits, so, counting down, you have:

 7: 0111
 6: 0110
 5: 0101
 4: 0100
 3: 0011
 2: 0010
 1: 0001
 0: 0000
-1: 1111
-2: 1110
-3: 1101
-4: 1100
-5: 1011
-6: 1010
-7: 1001
-8: 1000
Related Topic