Valid XHTML 1.0!

Negative numbers and binary representation.


Though details about bit/binary representation of negative numbers are not part of SCJP, it certainly helps to know about it.

Let us take a negative number for example, -7.

int a = -7; //declaration
The bit representation will be in 2’s complement form.

Steps to find 2’s Complement.
  1. Take binary representation of positive value (in this case, it is 7)

    0000 0000 0000 0000 0000 0000 0000 0111

  2. Take 1’s Complement of it.
    (Note : 1’s complement is calculated by inverting 1s with 0s and 0s with 1s.

    1111 1111 1111 1111 1111 1111 1111 1000

  3. Now add 1 to 1’s Complement to get 2’s complement.

    1111 1111 1111 1111 1111 1111 1111 1001

Therefore, -7 is stored as (1111 1111 1111 1111 1111 1111 1111 1001).

This example is only to show you that the MSB(most significant bit/ left most bit) of negative numbers is always 1. This fact will make it clear why the unsigned right shift of negative numbers results into a positive number.

For example,
int a = -7;
int b = a>>>1;

Questions related to shifting of integral data types can be easily solved if you bear this thing in mind.