Enter bitwise operators
A bitwise operator takes one or more values, treats them as sequences of bits, and performs operations on these bits rather than "human-readable" values.
Bitwise operators are available in most programming languages. For our purposes, let's explore how they're implemented in JavaScript.
Bitwise logical operators in JavaScript
JavaScript supports a total of 7 bitwise operators:
- 4 bitwise logical operators:
&
(Bitwise AND),|
(Bitwise OR),^
(Bitwise XOR), and~
(Bitwise NOT). - 3 bitwise shift operators:
<<
(Left shift),>>
(Sign-propagating right shift), and>>>
(Zero-fill right shift).
JavaScript's bitwise operators treat their operands as binary numbers -- sequences of 32 bits -- but return decimal numbers.
Here's an algorithm that JavaScript's bitwise logical operators follow:
- Operands are converted to 32-bit integers.
- If there are two operands, individual bits from the operands are matched into pairs: first operand's first bit to second operand's first bit, second bit to second bit, and so on.
- The operator is applied to each bit pair, which yields a binary result.
- The binary result is converted back to decimal form.
Possible operands and return values of bitwise operators are often illustrated with something called truth tables. Here's a truth table for all 4 bitwise logical operators available in JavaScript:
a | b | a AND b | a OR b | a XOR b | NOT a |
---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | 1 |
0 | 1 | 0 | 1 | 1 | - |
1 | 0 | 0 | 1 | 1 | 0 |
1 | 1 | 1 | 1 | 0 | - |
Before we discuss these operators in more detail, let's agree that we can present binary numbers in 3 different ways. Let's take the binary form of decimal 9 as an example:
0000000000000000000000000001001
represents all 32 bits of the number. This form is too long for most cases, but we'll use it when talking about binary shifts.1001
is the short form for the same number. Here, we include bits from the first bit that is set to 1 through the rightmost bit. We'll use this form in most examples.0b1001
is the format for expressing binary numbers in JavaScript source code. Apart from the0b
prefix, there's nothing fancy about it. We'll use this form in some code samples.