Bit wise shift operator with shift by negative number

前端 未结 1 1584
不知归路
不知归路 2020-12-17 21:20

I came across an interesting scenario, When working with bitwise shift operator. If the second operand is negative, how does the bitwise shift operation works? .

i.

1条回答
  •  囚心锁ツ
    2020-12-17 21:45

    But if b is neagtive, shouldn't it be an error at runtime?

    Not according to the Java Language Specification, section 15.19:

    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 (0b11111). The shift distance actually used is therefore always in the range 0 to 31, inclusive.

    So a shift of -32 actually ends up as a shift of 0, and a shift of -49 actually ends up as a shift of 15 - hence the results you saw.

    0 讨论(0)
提交回复
热议问题