Page 158 - JavaScript
P. 158

Chapter 15: Bitwise Operators - Real World


        Examples (snippets)




        Examples



        Number's Parity Detection with Bitwise AND


        Instead of this (unfortunately too often seen in the real code) "masterpiece":


         function isEven(n) {
             return n % 2 == 0;
         }

         function isOdd(n) {
             if (isEven(n)) {
                 return false;
             } else {
                 return true;
             }
         }


        You can do the parity check much more effective and simple:


         if(n & 1) {
             console.log("ODD!");
         } else {
             console.log("EVEN!");
         }


        (this is actually valid not only for JavaScript)


        Swapping Two Integers with Bitwise XOR (without additional memory
        allocation)



         var a = 11, b = 22;
         a = a ^ b;
         b = a ^ b;
         a = a ^ b;
         console.log("a = " + a + "; b = " + b);// a is now 22 and b is now 11


        Faster multiplication or division by powers of 2


        Shifting bits left (right) is equivalent to multiplying (dividing) by 2. It's the same in base 10: if we
        "left-shift" 13 by 2 places, we get 1300, or 13 * (10 ** 2). And if we take 12345 and "right-shift" by 3
        places and then remove the decimal part, we get 12, or Math.floor(12345 / (10 ** 3)). So if we
        want to multiply a variable by 2 ** n, we can just left-shift by n bits.






        https://riptutorial.com/                                                                             115
   153   154   155   156   157   158   159   160   161   162   163