位运算 - 零填充右移(>>>)的用法? [英] Bitwise operation - Zero-fill right shift (>>>) usages?

查看:658
本文介绍了位运算 - 零填充右移(>>>)的用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般而言,位移(>>,<< )允许我们通过分/乘 ^ 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(基体10)

= 2 (base 10)

对于数字:

同样, -9 GT;&GT; 2 收益率 -3 ,因为符号是preserved:

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)

但看&GT;&GT;&GT; ,其作用为正数,男相同,但不同的行为负numebrs:

But looking at >>> which acts the same for positive numbers ,m but behaves differently for negative numebrs :

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)

问:

在什么情况下我应该使用&GT;&GT;&GT; ?我不明白为什么我应该永远想从左边乱了我的负数垫零。

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.

这只是一个例子,其中位不PTED为数字间$ P $,我相信还有更多。我想你会在别的地方找到了一些更多的用途,尤其是为了模拟硬件电路/积木软件。

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.

这篇关于位运算 - 零填充右移(&GT;&GT;&GT;)的用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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