The left shift << and right shift >> operations are fundamental in binary data manipulation.
These operations simply shift the bits of a number one or more positions to the left or to the right.
Why are these two operations useful? If we remember, each digit of a binary number represents a factor that multiplies a power of 2.
For example,
| Binary | 0 | 1 | 0 | 1 | 1 | 0 |
|---|---|---|---|---|---|---|
| Power | 32 | 16 | 8 | 4 | 2 | 1 |
| Multiply by | 16 | 4 | 2 |
If we shift all bits to the left, each power has a number one higher. That is, it’s as if we had multiplied the entire number by two.
| << 1 | 1 | 0 | 1 | 1 | 0 | 0 |
|---|---|---|---|---|---|---|
| Power | 32 | 16 | 8 | 4 | 2 | 1 |
| Multiply by | 32 | 8 | 4 |
Conversely, shifting to the right is equivalent to dividing by two.
| >> 1 | 0 | 0 | 1 | 0 | 1 | 1 |
|---|---|---|---|---|---|---|
| Power | 32 | 16 | 8 | 4 | 2 | 1 |
| Multiply by | 8 | 2 | 1 |
These operations have the advantage of being very fast and efficient at the hardware level. Therefore, they are widely used internally by computers.
Left Shift
The left shift is an operation that moves all bits of a binary number to the left by a specified number of positions.
This shift is equivalent to multiplying the binary number by powers of two, depending on the number of positions shifted.
For example, shifting the binary number 1011 (11 in decimal) two positions to the left:
1011 (original binary)
<< 2 (left shift of two positions)
_________
101100 (result)
The result is 101100, which equals 44 in decimal. That is, it’s like having multiplied 1011 by 2 twice.
Right Shift
The right shift is an operation that moves all bits of a binary number to the right by a specified number of positions.
This shift is equivalent to performing integer division by powers of two, depending on the number of positions shifted.
For example, shifting the binary number 1011 (11 in decimal) two positions to the right:
1011 (original binary)
>> 2 (right shift of two positions)
_________
10 (result)
The result is 10, which equals 2 in decimal, which is the same as if we had divided 11 by 2 twice (discarding the remainders).
