简体   繁体   English

Java向左移动位时,溢出不会消失,但会在另一侧出现

[英]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 value 0x1f (0b11111). 就像右侧操作数受到掩码值0x1f (0b11111)的按位逻辑AND运算符&§15.22.1 )一样。 The shift distance actually used is therefore always in the range 0 to 31 , inclusive. 因此,实际使用的移动距离始终在031 ,包括031

So, i << 32 is the same as i << 0 , ie no shift at all. 因此, i << 32i << 0相同,即完全没有移位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM