ask a question

T

talk

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.
 
P

Patricia Shanahan

talk said:

If you really only want replies from guys, ignore the rest of this.
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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,139
Latest member
JamaalCald
Top