JavaScript Bitwise Operators
Subject: JavaScript
Bitwise operators in JavaScript perform operations on the binary representations of numbers. These operators work at the bit level and are often used in low-level programming, graphics, cryptography, and performance-critical code.
What Are Bits?
Every number is stored in binary form (composed of 0s and 1s). Bitwise operators allow direct manipulation of these individual bits. For example:
- 5 in binary →
0101 - 3 in binary →
0011
List of Bitwise Operators
| Operator | Name | Description |
|---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 |
| ` | ` | OR |
^ | XOR | Sets each bit to 1 if only one bit is 1 |
~ | NOT | Inverts all bits |
<< | Left Shift | Shifts bits to the left |
>> | Right Shift | Shifts bits to the right |
>>> | Zero-fill Right Shift | Shifts bits right and fills with 0 |
Example: Bitwise Operations
Explanation of Each Operator
Bitwise AND (&)
Bitwise OR (|)
Bitwise XOR (^)
Bitwise NOT (~)
Left Shift (<<)
Right Shift (>>)
Zero-fill Right Shift (>>>)
Use Cases
- File permission flags and masking
- Encryption and compression algorithms
- Optimized math operations
- Bit-level image or pixel manipulation
Key Takeaways
- Bitwise operators work directly on 32-bit binary numbers.
- Use
&,|,^to compare individual bits. ~flips bits, and shift operators (<<,>>,>>>) move bits.- Common in low-level tasks like performance tuning, cryptography, and graphics.