What is twos complement?

Two’s complement is a way of representing negative numbers in binary. Java uses this system to store negative numbers. The way it is done is, you flip all the bits and add one to it.  So twos compliment of 0000 0001 is

1111 1110 + 1 =1111 1111

In the table below, if you take any positive 32 bit integer, flip the bits and add 1, you will get the binary representation of its negative value.

 Decimal  Binary representation
 -2  11111111 11111111 11111111 11111110
 -1  11111111 11111111 11111111 11111111
 0  00000000 00000000 00000000 00000000
 1  00000000 00000000 00000000 00000001
 2  00000000 00000000 00000000 00000010

You  can verify this in Java (which uses 2’s complement to store negative numbers), using this line of code

 // gives you binary representation of -1
System.out.println(Integer.toBinaryString(-1));
//This will print 11111111111111111111111111111111

Why is it done this way?

One of the earlier proposed ways was to use the left most bit to represent the sign. Where left most 1 would be used to represent a negative number. So in that system a decimal 2 would be represented in binary as 0000 0010 (assuming 8 bit system for simplicity). And a -2 would be represented in binary as 1000 0010.

The problem using this way of representation was that if you add 2 and -2 in binary, you would expect 0000 0000 but what you got was 1000 0100. So if left most digit represents sign, then this is a -4.

The reason this was not used was because it screws up addition. In two’s complement, how ever, if you take the binary representations of +2 and -2, you would get all zeros (because the left most digit overflows out of the 32 bit address space). So addition works in 2’s complement.