Bitwise Operators


Bitwise Operators

🙋 Need help? Ask an expert now!

Bitwise operators are used on integer numbers. The operators are applied bit by bit. For example, the binary format for a 16-bit integer 300 is "00000001 00101100". This is how the computer stores using only 0s and 1s. There are a few operators that can be used with numbers. The chances of using this operator is pretty low, so don't worry too much about mastering this concept as long as you have a good idea of what's happening. The operator ~ turns all 0 to 1 and all 1 to 0. This is similar to the logical not operator (!) for boolean expressions but bit by bit. The "or" (|) and the "and" (&) behave like && and || but works bit by bit. The left shift (<<) and right shift (>>) operators shift (move) the bits to the left or to the right.

The bitwise operators are pretty confusing, so let's clear things up and see how each bitwise operator affected the bits. The first operator (|), looked through each bit of the numbers 3 and 5, and combined them to create one number. This operator changes all the combines the vertically aligned bits with one rule: "Anything with a 1 is converted to a 1". It's exactly what the || operator does, where true is 1 and false is 0. The & operator converts everything to 0 unless two 1s are present. The ~ operator as explained above simply changed all the 0s to 1s and 1s to 0s. The left shift and right shift operators shift the bits to the left or to the right by one as shown in the comments above.

Edit Me on GitHub!

Application Question

Consider the following code segment:

let a = 4; // 00000000 00000100
let b = 6; // 00000000 00000110
console.log(a | ~b);

What will the console.log() statement print to the console?