hi, guy
a program as listed below:
" short number = -32768;
System.out.println((short)(number >>> 1));"
i wonder why the output is -16384, not 16384?
the bit sequences of -32768 is 1000,0000,0000,0000;
so (number >>> 1) should be 0100,0000,0000,0000, it is 16384.
but why the output is 1100,0000,0000,0000, it is -16384.
Patricia Shanahan - 23 Apr 2006 14:24 GMT
> hi, guy
If you really only want replies from guys, ignore the rest of this.
> a program as listed below:
> " short number = -32768;
[quoted text clipped - 4 lines]
> so (number >>> 1) should be 0100,0000,0000,0000, it is 16384.
> but why the output is 1100,0000,0000,0000, it is -16384.
I think you are ignoring an implicit conversion to int. See the JLS
"unary numeric promotion (§5.6.1) is performed on each operand
separately" [15.19 Shift Operators at
http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#5121]
Your expression is equivalent to (short)(((int)number) >>> 1).
In hex (I'm not patient enough to write out that many bits), the first
conversion gets 0xffff8000. The unsigned right shift produces
0x7fffc000. The conversion back to short gets 0xc000, your final bit
pattern.
To get a zero fill shift of a short, you need to make the conversion to
int zero fill.
(short)( ( number & 0x0000ffff ) >>> 1)
Patricia
talk - 23 Apr 2006 16:39 GMT
Patricia
hi, thank you for your advice:)