Js Bitwise in JavaScript
? JavaScript Bitwise Operators
What are Bitwise Operators?
They operate on 32-bit integers at the binary level.
Useful for low-level programming, performance optimization, flags, masks, etc.
Convert operands to 32-bit signed integers internally.
List of Bitwise Operators
| Operator | Name | Description | Example |
|---|---|---|---|
& | AND | Bits set in both operands | 5 & 3 ? 1 |
| ` | ` | OR | Bits set in either operand |
^ | XOR (exclusive OR) | Bits set in one operand but not both | 5 ^ 3 ? 6 |
~ | NOT (one's complement) | Inverts bits | ~5 ? -6 |
<< | Left shift | Shift bits to the left | 5 << 1 ? 10 |
>> | Signed right shift | Shift bits to the right (sign-preserving) | 5 >> 1 ? 2 |
>>> | Unsigned right shift | Shift bits to the right (zero-fill) | 5 >>> 1 ? 2 |
How Bitwise Operators Work
Example with 5 and 3:
5in binary:000000000000000000000000000001013in binary:00000000000000000000000000000011
| Operation | Binary Result | Decimal Result |
|---|---|---|
5 & 3 | 00000000000000000000000000000001 | 1 |
| `5 | 3` | 00000000000000000000000000000111 |
5 ^ 3 | 00000000000000000000000000000110 | 6 |
~5 | 11111111111111111111111111111010 | -6 |
Example Usage
const flags = 5; // 0101 binary// Check if 1st bit is setif (flags & 1) { console.log("1st bit is set");}// Set 2nd bitconst newFlags = flags | 2; // sets second bitconsole.log(newFlags); // 7 (0111 binary)Notes
Bitwise operators always work on 32-bit integers.
Results are signed 32-bit integers.
Use unsigned right shift (
>>>) to avoid sign extension.
Want me to show you how bitwise can be used in flags, masks, or performance tricks?