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位.