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
444 views
in Technique[技术] by (71.8m points)

bit manipulation - Weird result of Java Integer left shift

I'm a little confused now by java left shift operation,

1<<31 =  0x80000000  --> this I can understand

But

1<<32 =  1       Why is this?
1<<33 =  2       

Looks like more shifting values, modulus 32 of the value is taken.

Thanks everybody for the replying and giving the quote from JLS.

I just want to know more. Any idea of the reason why it's designed in this way? Or is it just some convention? Apparently C doesn't have this quirk?

Thanks to @paxdiablo. Looks like C declares this behaviour undefined.

I have some personal assumption here:

ARM architecture Reference Manual A7.1.38

Syntax LSL Rd, Rm, #immed_5

where:

Rd Is the register that stores the result of the operation.

Rm Is the register containing the value to be shifted.

immed_5 Specifies the shift amount, in the range 0 to 31.

On instruction level, the immeidate immed_5 takes only 5 bits to avoid meaningless operations so as to save some instruction space. I guess high level languages just unitize this convention to avoid meaningless effort when compile to instructions.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

As per the Java Language Specification 15.19. Shift Operators (slightly paraphrased):

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & with the mask value 0x1f ,or 0b11111. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

That means that (for example) 33, being the 6-bit binary 100001, is reduced to the 5-bit 00001 before being used. So x << 33 is identical to x << 1.


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

...