“Regular” Logical vs. Bitwise Logical Operators

                JS bitwise operators:  &  |  ^   ~

                What is regular (non-bitwise) AND?

                                What is bitwise AND?

                What is regular OR?

                                What is bitwise OR?

                What is regular XOR?

                                What is bitwise XOR?

 

 

Bits, Bytes, and Bitwise

                What is a bit?

                What is a byte?

                How do integers work in bit format in JS?

                                Diagram of an example byte:

                                                Value:          27    26  25  24  23  22  21  20 

                                                Value:         128 64 32  16  8   4    2    1

     Content:    0      0    0    0   1   0    1    1

Content codes the integer  11 (eleven)

 

 

Converting Bit Format to Base 10

                Add up the values of the 1 bits

                Ignore the values of the 0 bits

                Let’s try a few more examples

 

 

Bitwise Operators – How They Work

Take two integers

                Compare the pairs of corresponding bits

                                & means AND each pair

                                | means OR each pair

                                ^ means XOR each pair

                                We could try some examples

Convert the result back into an integer

We could finish the examples

                …and try them in JavaScript

 

 

Translating Results Back to Integers

                Just add up the values of all the 1 bits

 

 

Optional Supplement: Converting integers to Bit Format

                Sort of reverse the process

                                Find the biggest power of 2 that fits into the integer

                                                Repeat until done

                                We could try a few examples

`               Negative numbers are represented differently

                                Look up “twos complement” for details

 

 

Optional Supplement: Negative integers

                Convert the positive version into bits

                Reverse all the bits

               Add 1

              That is the negative number

                    (Its “two’s complement” representation)

             We could try it

                   ~5+1  in JS gives -5