9

一般来说,位移 ( >> , <<) 允许我们除/乘^2

例子 :

      9 (base 10): 00000000000000000000000000001001 (base 2)
                   --------------------------------
 9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)

对于负数

同样,-9 >> 2产生-3,因为符号被保留:

     -9 (base 10): 11111111111111111111111111110111 (base 2)
                   --------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)

但是看看>>>哪个对于正数的行为相同,但对于负数的行为不同:

mdn

位从左边移入

我找不到任何 0从左移(使整数为正)从左移的原因/用法:

       -9 (base 10): 11111111111111111111111111110111 (base 2)
                     --------------------------------
 -9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)

问题 :

我应该在什么情况下使用>>> ?我不明白为什么我要从左边填充零并弄乱我的负数。

4

2 回答 2

6

一个简单且经常使用的用例是将变量转换为 32 位无符号整数 (UInt32)。当您执行变量 >>> 0 时,如果变量已经是 UInt32,则该变量将保持不变,否则将为 0。例如

在此处输入图像描述

使用示例:

function convert( arrayLikeVariable){
   // we dont know for sure if length is UInt32
   // e.g. arrayLikeVariable.length = "zavarakatranemia"
   // so we do >>> 0
   var len = arrayLikeVariable >>> 0 
   // Now len is UInt32 for sure. 
   [..]
   // code using the len
}

如果您想要一个完整的示例,请参见此处的 Polyfill:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

if (!Array.prototype.indexOf)  Array.prototype.indexOf = (function(Object, max, min){
  "use strict";
  return function indexOf(member, fromIndex) {
    if(this===null||this===undefined)throw TypeError("Array.prototype.indexOf called on null or undefined");

    var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len);
    if (i < 0) i = max(0, Len+i); else if (i >= Len) return -1;

    if(member===void 0){ for(; i !== Len; ++i) if(that[i]===void 0 && i in that) return i; // undefined
    }else if(member !== member){   for(; i !== Len; ++i) if(that[i] !== that[i]) return i; // NaN
    }else                           for(; i !== Len; ++i) if(that[i] === member) return i; // all else

    return -1; // if the value was not found, then return -1
  };
})(Object, Math.max, Math.min);
于 2017-11-23T08:23:13.157 回答
5

假设您正在编写一些东西来模仿一个硬件,特别是一个移位寄存器

为了让事情更容易,我将使用 8 位而不是 32 位,如您的问题。

每次我们想向这个移位寄存器输入一个高位时,我们可以加 128,因为它会使最左边的位为 1。

// Assume n is initialised to 0, so n = 00000000 in binary
n += 128;                    // now n = 10000000 in binary

如果我们每次你想模拟一个时钟周期时都使用 >>> 进行移位,那么在 8 个“时钟周期”之后,我们将在最右边的位上得到 1。如果我们读出最右边的位,那么我们将得到 8 个周期前馈入最左边的位的延迟版本。


这只是位不被解释为数字的一个例子,我相信还有更多。我认为您会在其他地方找到更多用途,尤其是在旨在模仿硬件电路/构建块的软件中。

于 2013-11-18T17:48:25.450 回答