How ones compliment of ~0 gives -1

I know the method first we invert the bits and then add 1 to it(2 compliment) and this method works on every integer except 0???
0000>>1111+1=0000 but ~0= -1

works fine on other integers …Please help

Your equations represent different calculations. The first calculates -0=0, while the second just inverts all bits. Here’s how ~0 gives -1:

~0000 = 1111 = 1110+1=~0001+1=-1

1 Like

~ operator is 1’s compliment.

3 Likes

the very first bit represent the sign which is 0 for any positive value
as ~ flips all the bits including the sign bit
~(0000000) = (11111111) = -(1<<7) + 01111111 = -(1<<7) + (1<<7) -1 = -1

1 Like

suppose I want to caluclate ~5 then the method i used 0110(5)—1001(flliping)—1001+1----1010(-6) which gives right output (cout<<~5=-6)and my method gives right output for every integer except 0 .WHY???

Suppose I want to caluclate ~5 then the method i used 0110(5)—1001(flliping)—1001+1----1010(-6) which gives right output (cout<<~5=-6)and my method gives right output for every integer except 0 .WHY???

Suuppose I want to caluclate ~5 then the method i used 0110(5)—1001(flliping)—1001+1----1010(-6) which gives right output (cout<<~5=-6)and my method gives right output for every integer except 0 .WHY???

for ~5 => ~ 0101 : 1010 == -8 + 2 = -6
for 0 => ~0000 : 1111 == -8 + 4 + 2 + 1 == -1
just for (~n) == -1 * n - 1

1 Like

I suspect you are confused with one’s and two’s complement. This video of Computerphile hopefully gives a good explanation. Below a quick summary.

Name Range (4 bit) Method
signed magnitude -7 to 7 leftmost bit denotes sign, others the magnitude
one’s complement -7 to 7 -a is just the value a with all bits flipped, i.e. ~a
two’s complement -8 to 7 -a = ~a+1, represents the value modulo 2^4

All modern systems use two’s complement to represent negatives, because it makes additions a lot easier. So to answer your original question:
~0 is the one’s complement of 0000, which is 1111
-1 is the two’s complement of 0001, which is 1110+1=1111
These have the same sequence of bits, and so are equal.

In general you should not think of ~ as a negative, but as a bitwise not. Bitwise means it applies it to each bit instead of interpreting both values as booleans.

1 Like

5 is 0101 (not 0110), so its 1’s complement is 1010 which is -6.

1 Like

That’s first Compliment, So you are basically reversing bits in it without adding any extra to it.
~(0000) => (1111) => (-1)

1 Like