Negative numbers and binary representation

Use -7 as sample.

int a = -7; //declaration, notice that int is 4 bytes, so 32 bits.
The bit representation will be in 2’s complement form.

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

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

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;

posted @ 2011-12-01 08:12  allenbackpacker  阅读(186)  评论(0编辑  收藏  举报