# bit-manipulation Java：对负数进行右移

``````i = -5 >> 3;  shift bits right three time
``````

`````` MSB
+----+----+----+---+---+---+---+---+
|  1 |  1 | 1  | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
7    6   5    4   3   2   1   0
^  This seventh, the left most bit is SIGN bit
``````

``````                        this 3 bits are shifted
out and loss
MSB                   (___________)
+----+----+----+---+---+---+---+---+
|  1 |  1 | 1  | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
| \                 \
|  ------------|     ----------|
|              |               |
▼              ▼               ▼
+----+----+----+---+---+---+---+---+
|  1 |  1 | 1  | 1 | 1 | 1 | 1 | 1 |
+----+----+----+---+---+---+---+---+
(______________)
The sign is
propagated
``````

``````                        this 3 bits are shifted
out and loss
MSB                   (___________)
+----+----+----+---+---+---+---+---+
|  0 |  0 | 0  | 0 | 0 | 1 | 0 | 1 |
+----+----+----+---+---+---+---+---+
| \                 \
|  ------------|     ----------|
|              |               |
▼              ▼               ▼
+----+----+----+---+---+---+---+---+
|  0 |  0 | 0  | 0 | 0 | 0 | 0 | 0 |
+----+----+----+---+---+---+---+---+
(______________)
The sign is
propagated
``````

[你的答案]

``````i = -5 >>> 3;  Unsigned shift bits right three time
``````

``````                        this 3 bits are shifted
out and loss
MSB                   (___________)
+----+----+----+---+---+---+---+---+
|  1 |  1 | 1  | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
| \                 \
|  ------------|     ----------|
|              |               |
▼              ▼               ▼
+----+----+----+---+---+---+---+---+
|  0 |  0 | 0  | 1 | 1 | 1 | 1 | 1 |
+----+----+----+---+---+---+---+---+
(______________)
These zeros
are inserted
``````

• 无符号右移运算符`>>>`产生一个纯值，即左操作数右移，零扩展`0` ，由右操作数指定的位数。

• `>>``<<` ，operator `>>>`运算符也从不抛出异常。

• 无符号右移运算符的每个操作数的类型必须是整数数据类型，否则会发生编译时错误。

• `>>>`运算符可以对其操作数执行类型转换; 与算术二元运算符不同，每个操作数都是独立转换的。 如果操作数的类型是byte，short或char，则在计算运算符的值之前将该操作数转换为int。

• 无符号右移运算符生成的值的类型是其左操作数的类型。 `LEFT_OPERAND >>> RHIGT_OPERAND`

• 如果左操作数的转换类型是int，则只使用右操作数值的五个最低有效位作为移位距离。 （ 即2 5 = 32位= int中的位数
因此，移位距离在0到31的范围内。

这里， `r >>> s`产生的值与：

``````s==0 ? r : (r >> s) & ~(-1<<(32-s))
``````
• 如果左操作数的类型很长，则只使用右操作数值的六个最低有效位作为移位距离。（ 即2 5 = 64位=长位数

这里， `r >>> s`产生的值与以下相同：

``````s==0 ? r : (r >> s) & ~(-1<<(64-s))
``````

java bit-manipulation bitwise-operators bit-shift negative-number

``````int n = -15;
System.out.println(Integer.toBinaryString(n));
int mask = n >> 31;
``````

``````11111111111111111111111111110001
11111111111111111111111111111111
``````