[英]Java when shifting bits left, overflows dont disappear but appear back on other side
int i = 0x000000FF;
i = i << 24;
message = String.format("0x%08X", i);
// prints the message 0xFF000000
int i = 0x000000FF;
i = i << 32;
message = String.format("0x%08X", i);
// prints the message 0x000000FF
I was expecting the second one to print 0x00000000 我期待第二个打印0x00000000
What is going on? 到底是怎么回事?
See Java Language Specification 15.19. 参见Java语言规范15.19。 Shift Operators :
移位运算符 :
If the promoted type of the left-hand operand is
int
, then only the five lowest-order bits of the right-hand operand are used as the shift distance.如果左侧操作数的提升类型为
int
,则仅将右侧操作数的五个最低阶位用作移位距离。 It is as if the right-hand operand were subjected to a bitwise logical AND operator&
( §15.22.1 ) with the mask value0x1f
(0b11111).就像右侧操作数受到掩码值
0x1f
(0b11111)的按位逻辑AND运算符&
( §15.22.1 )一样。 The shift distance actually used is therefore always in the range0
to31
, inclusive.因此,实际使用的移动距离始终在
0
到31
,包括0
和31
。
So, i << 32
is the same as i << 0
, ie no shift at all. 因此,
i << 32
与i << 0
相同,即完全没有移位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.