Bitwise operation - Zero-fill right shift (>>>) usages?

后端 未结 2 1699
生来不讨喜
生来不讨喜 2021-01-02 10:12

Generally speaking, bit shifting (>> , <<) allows us to divide / multiply by ^2

Example :

      9 (base 10): 0         


        
相关标签:
2条回答
  • 2021-01-02 11:02

    Let's say you were programming something to mimic a piece of hardware, specifically a shift register.

    To make things easier I'll use 8 bits instead of 32 bits as in your question.

    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
    

    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.

    0 讨论(0)
  • 2021-01-02 11:07

    A simple and often use case is to convert a variable to 32-bit unsigned integer(UInt32). When you do variable >>> 0, the variable will stay the same if it is already a UInt32 and will be 0 if it is not. e.g.

    using example:

    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
    }
    

    If you want a complete example see the Polyfill here:

    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);
    
    0 讨论(0)
提交回复
热议问题