Bitwise operation - Zero-fill right shift (gt;gt;gt;) usages?(按位运算 - 零填充右移 (gt;gt;gt;) 用法?)
问题描述
一般来说,位移位(>> , <<
)允许我们除以/乘以 ^2
Generally speaking, bit shifting (>> , <<
) allows us to divide / multiply by ^2
例子:
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
对于负数字:
同样,-9 >>2
产生 -3
,因为符号被保留:
Likewise, -9 >> 2
yields -3
, because the sign is preserved:
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
但是看看 >>>
它对于正数的行为相同,但对于负数的行为不同:
But looking at >>>
which acts the same for positive numbers, but behaves differently for negative numbers :
mdn
零位从左边移入
我找不到从左侧移动 0
的任何原因/用法(这使得整数为正数):
I can't find any reason / usage for shifting 0
from the left ( which makes the whole number positive) from the left :
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
问题:
在什么情况下我应该使用 >>>
?我不明白我为什么要从左边填充零并弄乱我的负数.
In what scenarios should I use >>>
? I don't understand why should I ever want to pad zeros from the left and mess my negative number.
推荐答案
假设你正在编写一些东西来模仿一个硬件,特别是 移位寄存器.
Let's say you were programming something to mimic a piece of hardware, specifically a shift register.
为了方便起见,我将使用 8 位而不是您的问题中的 32 位.
To make things easier I'll use 8 bits instead of 32 bits as in your question.
每次我们想向这个移位寄存器输入一个高位时,我们可以添加 128,因为它会使最左边的位变为 1.
We can add 128 every time we want to feed a high bit into this shift-register, since it will make the leftmost bit 1.
// Assume n is initialised to 0, so n = 00000000 in binary
n += 128; // now n = 10000000 in binary
如果我们每次你想模拟一个时钟周期时都使用 >>> 进行移位,那么在 8 个时钟周期"之后,我们将在最右边有那个 1.如果我们读出最右边的位,那么我们将得到 8 个周期前馈入最左边的位的延迟版本.
If we shift using >>> every time you want to simulate a clock cycle, then after 8 "clock cycles" we will have that 1 at the rightmost bit. If we read that rightmost bit out then we will get a delayed version of what was fed into the leftmost bit 8 cycles ago.
这只是位不被解释为数字的一个例子,我相信还有更多.我认为您会在其他地方找到更多用途,尤其是在旨在模仿硬件电路/构建块的软件中.
This is only one example where the bits are not interpreted as a number, and I am sure there are many more. I think you'll find a few more uses elsewhere, especially in software meant to mimic hardware circuits/building blocks.
这篇关于按位运算 - 零填充右移 (>>>) 用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!