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

后端 未结 2 511
礼貌的吻别
礼貌的吻别 2020-12-03 09:03

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 &l         


        
2条回答
  •  不思量自难忘°
    2020-12-03 09:23

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

提交回复
热议问题