JavaScript provides three bitwise shift operators. They allow you to shift bits to the left or right, either preserving or discarding the sign bit.
| Operator | Example | Description |
|---|---|---|
<< | a << 2 | Shifts bits of a to the left by 2 positions |
>> | a >> 2 | Shifts bits of a to the right by 2 positions (signed) |
>>> | a >>> 2 | Shifts bits of a to the right by 2 positions (unsigned) |
Left Shift (<<)
Moves bits to the left and fills the right side with zeros.
Example: 5 << 1 → 10
Signed Right Shift (>>)
Preserves the sign bit (most significant bit).
Example: -8 >> 1 → -4
Unsigned Right Shift (>>>)
Does not preserve the sign bit. Useful when working with raw binary data.
Example: -8 >>> 1 → large positive integer (because sign bit becomes zero)



コメント