Akash
Akash

Reputation: 5012

Complementing binary numbers

When I complement 1 (~1), I get the output as -2. How is this done internally?

I first assumed that the bits are inverted, so 0001 becomes 1110 and then 1 is added to it, so it becomes 1111 which is stored, how is the number then retrieved?

Upvotes: 1

Views: 252

Answers (2)

Dan
Dan

Reputation: 10786

Well, no. When you complement 1, you go just invert the bits:

 1  ==  0b00000001
~1  ==  0b11111110

And that's -2 in two's complement, which is the way your computer internally represents negative numbers. See http://en.wikipedia.org/wiki/Two's_complement but here are some examples:

-1  ==  0b11111111
-2  ==  0b11111110
 ....
-128==  0b10000000
+127==  0b01111111
 ....
+2  ==  0b00000010
+1  ==  0b00000001
 0  ==  0b00000000

Upvotes: 3

Charles Bretana
Charles Bretana

Reputation: 146409

Whar do you mean "when I complement 1 (~1)," ? There is what is called Ones-complement, and there is what is called Twos-Complement. Twos-Complement is more common (it is used on most computers) as it allows negative numbers to be added and subtracted using the same algorithm as postive numbers.

Twos-Complement is created by taking the binary representation of the postive number and switching every bit from 1 to 0 and from 0 to 1, and then adding one

 5   0000 0101  
 4   0000 0100   
 3   0000 0011  
 2   0000 0010  
 1   0000 0001  
 0   0000 0000  
-1   1111 1111  
-2   1111 1110  
-3   1111 1101  
-4   1111 1100 
-5   1111 1011 
etc.

Upvotes: 1

Related Questions