java-了解无符号右移

JLS 15.19描述了>>>的公式.运算符.

 

The value of n >>> s is n right-shifted s bit positions with
zero-extension, where:

If n is positive, then the result is the same as that of n >> s.

If n is negative and the type of the left-hand operand is int, then
the result is equal to that of the expression (n >> s) + (2 << ~s).

If n is negative and the type of the left-hand operand is long, then
the result is equal to that of the expression (n >> s) + (2L << ~s).

为什么n>>> s =(n> s)(2

最佳答案

如果n为负,则表示符号位已置1.

>>> s表示向右移动s位置,将零引入空出的槽中.

>> s表示向右移动s位置,将符号位的副本引入到空出的插槽中.

例如.

 

10111110000011111000001111100000 >>> 3 == 00010111110000011111000001111100

10111110000011111000001111100000 >>  3 == 11110111110000011111000001111100
复制代码

显然,如果n不为负,则n> 1. s和n>> s是相同的.如果n为负,则差将由左侧的s组成,后跟全零.

换一种说法:

 

(n >>> s) + X == n >> s        (*)
复制代码

其中X由s组成,后跟32-s个零.

因为X中有32-s个零,所以X中最右边的一个出现在1 <1的位置. (32-s),等于2<< (31-s),与2<< ?s(因为?s == -1-s,并且移位量对int取模32). 现在,当您添加2<< ?s到X?你得到零!让我们在s == 7的情况下对此进行演示.请注意,进位从左侧消失.

  11111110000000000000000000000000
+ 00000010000000000000000000000000
  ________________________________
  00000000000000000000000000000000
复制代码

因此,-X == 2 << ?s.因此,在(*)的两边加上-X,我们得到

n >>> s == (n >> s) + (2 << ~s)
复制代码

长期以来,它是完全一样的,只是移位量以64为模,因为long具有64位.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值