Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Findbugs warning: Integer shift by 32 -- what does it mean?

I was scanning a third party source code using Findbugs (just to be cautious before integrating into it mine), and found the following warning:

long a = b << 32 | c

Bug: Integer shift by 32 Pattern id: ICAST_BAD_SHIFT_AMOUNT, type: BSHIFT, category: CORRECTNESS

The code performs an integer shift by a constant amount outside the range 0..31. The effect of this is to use the lower 5 bits of the integer value to decide how much to shift by. This probably isn't want was expected, and it at least confusing.

Could anyone please explain what exactly does the above mean?

Thanks! (I am quite a newbie in Java programming)

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

From the Java Language Specification:

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 & (§15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

So if b is an int, the expression is identical to

long a = b | c;

which I highly doubt is what is intended. It should probably have been

long a = ((long) b << 32) | c;

(If b is already a long, the code is correct and FindBugs is mistaken about the bug).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...