Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

java - Bitwise shift operators. Signed and unsigned

I'm practising for the SCJP exam using cram notes from the Internet.

According to my notes the >> operator is supposed to be signed right shift, with the sign bit being brought in from the left. While the left shift operator << is supposed to preserve the sign bit.

Playing around however, I'm able to shift the sign with the << operator (f.e. Integer.MAX_VALUE << 1 evaluates to -2, while I'm never able to shift the sign with the >> operator.

I must be misunderstanding something here, but what?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

">>" is signed because it keeps the sign. It uses the most left digit in binary representation of a number as a filler. For example:

    | this value is used as a filler 
    11011011 
 >> 11101101  

    01010010
 >> 00101001 

">>>" is unsigned version of this operator. It always use zero as a filler:

    11011011 
>>> 01101101  

    01010010
>>> 00101001

In binary representation the most left digit determines sign of the number. So, if it's '1' then we have negative value and if it's '0' - then our number is positive. That's why using the most left digit as a filler allows to keep sign permanent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...