In Java, when using bitshifts, why does 1 << 32 != 1 << 31 << 1?

前端 未结 2 813
不思量自难忘°
不思量自难忘° 2020-12-15 23:08
int a = 1 << 32;
int b = 1 << 31 << 1;

Why does a == 1? b is 0

2条回答
  •  -上瘾入骨i
    2020-12-15 23:22

    There is some difference in how processors implement shift instructions.

    For instance, IIRC, ARM processors (32-bit ISA) take the least significant byte of the shifting register. (Shifts are not actually standalone instructions on ARM).

    So long as the underlying processor has a vaguely sensible way to shift, it's easier to clear all but the least significant bits (one instruction usually) than to check if the shift is large and branch (actually on the ARM this only typically adds one instruction because all instructions are conditional).

提交回复
热议问题