Page 76 - JavaScript
P. 76

a = 0b1001 >>> 2; // a === 0b0010
         a = 0b1001 >>> 3; // a === 0b0001


        A negative 32bit value always has the left most bit on:


         a = 0b11111111111111111111111111110111 | 0;
         console.log(a); // -9
         b = a >> 2;     // leftmost bit is shifted 1 to the right then new left most bit is set to on
         (1)
         console.log(b); // -3
         b = a >>> 2;    // leftmost bit is shifted 1 to the right. the new left most bit is set to off
         (0)
         console.log(b); // 2147483643


        The result of a >>> operation is always positive.
        The result of a >> is always the same sign as the shifted value.


        Right shift on positive numbers is the equivalent of dividing by the Math.pow(2,n) and flooring the
        result:


         a = 256.67;
         n = 4;
         result = (a >> n) === Math.floor( Math.floor(a) / Math.pow(2,n) );
         // result is true
         a = a >> n; //  16

         result = (a >>> n) === Math.floor( Math.floor(a) / Math.pow(2,n) );
         // result is true
         a = a >>> n; //  16


        Right shift zero fill (>>>) on negative numbers is different. As JavaScript does not convert to
        unsigned ints when doing bit operations there is no operational equivalent:


         a = -256.67;
         result = (a >>> n) === Math.floor( Math.floor(a) / Math.pow(2,n) );
         // result is false


        Bitwise assignment operators


        With the exception of not (~) all the above bitwise operators can be used as assignment operators:


         a |= b;   // same as: a = a | b;
         a ^= b;   // same as: a = a ^ b;
         a &= b;   // same as: a = a & b;
         a >>= b;  // same as: a = a >> b;
         a >>>= b; // same as: a = a >>> b;
         a <<= b;  // same as: a = a << b;



        Warning: Javascript uses Big Endian to store integers. This will not always match the Endian of
        the device/OS. When using typed arrays with bit lengths greater than 8 bits you should check if the
        environment is Little Endian or Big Endian before applying bitwise operations.




        https://riptutorial.com/                                                                               33
   71   72   73   74   75   76   77   78   79   80   81