按位运算 - 零填充右移(>>>)用法?

Roy*_*mir 8 javascript binary bit-manipulation

一般来说,bit shift(>> , <<)允许我们分频/乘以^2

示例:

      9 (base 10): 00000000000000000000000000001001 (base 2)
                   --------------------------------
 9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
Run Code Online (Sandbox Code Playgroud)

= 2(基数10)

对于负数:

同样,-9 >> 2收益率-3,因为符号被保留:

     -9 (base 10): 11111111111111111111111111110111 (base 2)
                   --------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
Run Code Online (Sandbox Code Playgroud)

但是看看>>>哪些行为对于正数而言是相同的,但是对于负数,行为却不同:

MDN

位从左侧移入

0从左边找不到任何理由/用法从左边移动 (这使得整个数字为正):

       -9 (base 10): 11111111111111111111111111110111 (base 2)
                     --------------------------------
 -9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
Run Code Online (Sandbox Code Playgroud)

题 :

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

Mik*_*old 5

假设您正在编写一些程序来模拟硬件,特别是移位寄存器

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

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

// Assume n is initialised to 0, so n = 00000000 in binary
n += 128;                    // now n = 10000000 in binary
Run Code Online (Sandbox Code Playgroud)

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


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


Tho*_*tos 5

一个简单且经常使用的情况是将变量转换为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
}
Run Code Online (Sandbox Code Playgroud)

如果需要完整的示例,请在此处查看Polyfill:

https://developer.mozilla.org/zh-CN/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);
Run Code Online (Sandbox Code Playgroud)