Binary Notations

Negative numbers are handled different in different languages, OS:es, devices etc. The following are some of the most popular, with simple bytes (8 bits) as example.

Signed Magnitude

The most significant bit (MSB) is set to 1 if the value should be negative. I.e. 12 = 00001100, -12 = 10001100

One´s Complement

Flip the bits of a positive number to get the negative one. The MSB should be 1 when it is a negative number. I.e. 22 = 00010110, -22 = 11101001. Vice versa for getting the positive value from a negative one, that is, take the negative number and flip it, add one.

Two´s Complement

Used by Sun´s Java. Similar to One´s Complement, but one (1) must be added after flipping. I.e. 15 = 00001111, -15 = 11110001. It can be explained in Java code like below, where target will hold -7, the negative of 7 in source. The tilde ~ is the bitwise inversion operator.

 int source = 7; int target; target = ~source; target++; System.out.println("Converted [" + source + "] to [" + target + "]");