What are Bitwise Operators?
Bitwise operators treat their operands as bits: zeroes and ones. There are three bitwise operators that you need to know about:
- Bitwise AND:
&
- Bitwise OR:
|
- Bitwise NOT:
~
Each of them used for different purposes.
The bitwise AND operator
The Bitwise AND operator returns 1 in each bit position for which the corresponding bits of both operands are 1. For example:
Copied to clipboard!
0 & 0 // returns 0
0 & 1 // returns 0
1 & 0 // returns 0
1 & 1 // returns 1
The bitwise OR operator
Unlike the AND operator, the bitwise OR operator returns 1 in each bit position for which the corresponding bits of either one of the operands are 1. For example:
Copied to clipboard!
0 | 0 // returns 0
0 | 1 // returns 1
1 | 0 // returns 1
1 | 1 // returns 1
The bitwise NOT operator
The bitwise NOT operator is used to invert the bits of its operand. For example:
Copied to clipboard!
~0 // returns -1
~-1 // returns 0
~1 // returns -2
~-2 // returns 1
Resources:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews