previous | start | next

Computing the two's complement with bit operations

As a start, observe what happends if we add ~b (the 1's complement of
b) to b:


   b:  0000 0000 0000 0000 0000 0000 0010 0101
  ~b:  1111 1111 1111 1111 1111 1111 1101 1010
       ---------------------------------------
       1111 1111 1111 1111 1111 1111 1111 1111

All 1's. This is not what we want. But if we add the value 1 to this,
we get 0:

Carry 11111 1111 1111 1111 1111 1111 1111 111
       1111 1111 1111 1111 1111 1111 1111 1111
       0000 0000 0000 0000 0000 0000 0000 0001
       ---------------------------------------
       0000 0000 0000 0000 0000 0000 0000 0000

So 
      b + ~b + 1 = 0

But this means we can take the representation ~b + 1 for -b.

     ~b:  1111 1111 1111 1111 1111 1111 1101 1010
      1:  0000 0000 0000 0000 0000 0000 0000 0001
          ---------------------------------------
 ~b + 1:  1111 1111 1111 1111 1111 1111 1101 1011

~b + 1 is called the 2's complement of b.

Check that the two's complement of b added to b is 0:
Carry bits: 11111 1111 1111 1111 1111 1111 1111 111
         b:  0000 0000 0000 0000 0000 0000 0010 0101
      ~b+1:  1111 1111 1111 1111 1111 1111 1101 1011
             ---------------------------------------
             0000 0000 0000 0000 0000 0000 0000 0000




previous | start | next