ed suttner

Greenhorn

Posts: 13

posted 14 years ago

I do not understand this example found in one of the books I am using to prepare for the programmer exam:

int i = 12;

int result = i >> 2; //result is 3

byte b = -42

int result = b >> 4; //result is -3

I do not understand why the first one is 3 and the second one is -3? (I do understand why it is a negative number, I just do not understand why it is -3) The first one 12/2*2 = 3. Why is -42/2*2*2*2 = -42/16 = -3? Thanks.

int i = 12;

int result = i >> 2; //result is 3

byte b = -42

int result = b >> 4; //result is -3

I do not understand why the first one is 3 and the second one is -3? (I do understand why it is a negative number, I just do not understand why it is -3) The first one 12/2*2 = 3. Why is -42/2*2*2*2 = -42/16 = -3? Thanks.

Phil Chuang

Ranch Hand

Posts: 251

posted 14 years ago

You need to think of negative numbers in "two's complement" - that is, in order to get a negative number, you invert the bits and add 1 to it.

A short 8-bit example:

94 = 0101 1110

-94 = 1010 0001 + 1 = 1010 0010

so looking at -42,

42 = 0010 1010

-42 = 1101 0101 + 1 = 1101 0110

42 >> 4 = 0000 0010 = 2

-42 >> 4 = 1111 1101

(the far left bit always propagates right on a shift right)

invert 1111 1101 = 0000 0010 = 2

add 1, you get 3

so -42 >> 4 = -3

A short 8-bit example:

94 = 0101 1110

-94 = 1010 0001 + 1 = 1010 0010

so looking at -42,

42 = 0010 1010

-42 = 1101 0101 + 1 = 1101 0110

42 >> 4 = 0000 0010 = 2

-42 >> 4 = 1111 1101

(the far left bit always propagates right on a shift right)

invert 1111 1101 = 0000 0010 = 2

add 1, you get 3

so -42 >> 4 = -3

ed suttner

Greenhorn

Posts: 13

posted 14 years ago

Thanks Phil. I guess what got me confused was in the book it said that a x >> 4 is exactly the same as x / 2^4 amd that x << 4 is exactly the same as x * 2^4. So when I saw this:

byte b = -42

int result = b >> 4; //result is -3

I thought it was the same as -42 / 2^4 = -42 / 2*2*2*2 = -42/16 = -2.625.

I guess that I will not use the short cut described in the book. Thanks.

byte b = -42

int result = b >> 4; //result is -3

I thought it was the same as -42 / 2^4 = -42 / 2*2*2*2 = -42/16 = -2.625.

I guess that I will not use the short cut described in the book. Thanks.

It is sorta covered in the JavaRanch Style Guide. |