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

后端 未结 2 1713
生来不讨喜
生来不讨喜 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: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);
    

提交回复
热议问题