Page 154 - JavaScript
P. 154

Chapter 14: Bitwise operators




        Examples



        Bitwise operators


        Bitwise operators perform operations on bit values of data. These operators convert operands to
        signed 32-bit integers in two's complement.


        Conversion to 32-bit integers



        Numbers with more than 32 bits discard their most significant bits. For example, the following
        integer with more than 32 bits is converted to a 32-bit integer:


         Before: 10100110111110100000000010000011110001000001
         After:              10100000000010000011110001000001



        Two's Complement



        In normal binary we find the binary value by adding the 1's based on their position as powers of 2 -
        The rightmost bit being 2^0 to the leftmost bit being 2^n-1 where n is the number of bits. For
        example, using 4 bits:


         // Normal Binary
         // 8 4 2 1
            0 1 1 0  => 0 + 4 + 2 + 0 => 6


        Two complement's format means that the number's negative counterpart (6 vs -6) is all the bits for
        a number inverted, plus one. The inverted bits of 6 would be:


         // Normal binary
            0 1 1 0
         // One's complement (all bits inverted)
            1 0 0 1  => -8 + 0 + 0 + 1 => -7
         // Two's complement (add 1 to one's complement)
            1 0 1 0  => -8 + 0 + 2 + 0 => -6


        Note: Adding more 1's to the left of a binary number does not change its value in two's
        compliment. The value 1010 and 1111111111010 are both -6.


        Bitwise AND



        The bitwise AND operation a & b returns the binary value with a 1 where both binary operands
        have 1's in a specific position, and 0 in all other positions. For example:





        https://riptutorial.com/                                                                             111
   149   150   151   152   153   154   155   156   157   158   159