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