位运算bit

# 以下位运算均总结语32位有符号位语言

# 按位否 Bitwise Not (~)

  • 按位取反 ~N 相当于 -(N + 1),~55 => -(55 + 1) => -56
  • 应用:
       ~(-1) = 0
    
       function boolIndex(index){
           return Boolean(~index)
       }
    
       boolIndex([1,2,3].indexOf(1)) //true
    

# 按位与 Bitwise And (&)

  • 按位 N1 & N2, 同位为1才为1

  • 应用:

    1. N & 0 = 0
    2. N & 1 = N
    3. bit mask 位掩码
         const mask = 0b11110000;  //js二进制数字表示
         mask & 22 // 16  确保了22的低四位为0,高四位不变
      
       /**
        *  判定奇偶
        */
      
        function isOdd(int){
            return int & 1 === 1;
        }
      
        function isEvent(int){
            return int & 1 === 0;
        }
      

# 按位或(|)、按位异或(^)

  • just like (&)

# 左移(<<)

  • N1 << N2 => N1 * Math.pow( 2 , N2)

  • 应用:

    1.      130 << 3 === 130 * Math.pow(2,3) //true
      
    2.         /**
              * color rgb值转Hex16进制数
              */   
      
              function rgb2Hex([red = 0,green = 0, blue = 0] = []){
                  return `#${ red << 16 | green << 8 | blue.toString(16)}`;
              }
      

# 右移(>>)

  • N1 >> N2 => Math.floor(N1 / Math.pow( 2, N2))
  • 应用:
    1. // 向下取整 
      
      Math.floor(1.1) === 1.1 >> 0 //true 
      
    2.    /**
          *  color hex16进制转rgb
          */  
          function hex2Rgb(hex){
              const mask = 0xff;
              let re = /^#?([0-9a-f]{6})$/i
              hex = hex.replace(re,'$1');
              hex = Number(`0x${hex}`);
              return [
                  (hex >> 16) & mask,  // red
                  (hex >> 8) & mask,   // green
                  hex & mask         // blue
              ]
          }