java位操作>>>转移 [英] java Bit operations >>> shift

查看:163
本文介绍了java位操作>>>转移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么如果

int x = -1 // binary: 11111111111111111111111111111111
x = x >>> 31; 

我们有00000000000000000000000000000001

we have 00000000000000000000000000000001

但是如果

int x = -1
x = x >>> 32;

我们有11111111111111111111111111111111(再次-1)

we have 11111111111111111111111111111111 (again -1)

但不是00000000000000000000000000000000?

but not 00000000000000000000000000000000 ?

推荐答案

来自 JLS第15.19节


如果左侧操作数的提升类型为int,则只有右侧操作数的五个
最低位用作shift
距离
。就好像右手操作数受到
按位逻辑AND运算符& (§15.22.1),掩码值 0x1f
(0b11111)
。因此,实际使用的移动距离始终在
范围内 0到31 ,包括在内。

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.

强调我的。所以:

x >>> n

相当于:

x >>> n & 0x1f  // or x >>> n % 32

所以, x>>> 32 相当于 x>>> 32& 0x1f < ==> x>>> 0 == x

So, x >>> 32 is equivalent to x >>> 32 & 0x1f <==> x >>> 0 == x.

所以经验法则是,每当你将数字移动 32 的倍数时( int 32位),你得到相同的值。

So the Rule of Thumb is, whenever you shift a number by a multiple of 32(int is 32 bits), you get back the same value.

这篇关于java位操作&gt;&gt;&gt;转移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆