How bit shifts work
A left shift moves all bits to a higher position.
A right shift moves all bits to a lower position.
A left shift of one position multiplies the value by 2. A right shift of one position divides it by 2.
Try bit shifts in the bit editor
The result of 1 shifted left by 4 positions. Edit the expression or select a bit to flip it.
7
6
5
4
3
2
1
0
16
value · 8 bits · unsigned
- hex
- 0x10
Bit width
Shift
Bit shifts step by step
Shift the value 1 left by four positions:
- Write the value: 00000001.
- Move every bit four positions to the left.
- Fill the empty low positions with 0.
- The result is 00010000, which is 16.
The value 1 shifted left
| Expression | Binary | Decimal |
|---|---|---|
| 1 << 0 | 00000001 | 1 |
| 1 << 1 | 00000010 | 2 |
| 1 << 2 | 00000100 | 4 |
| 1 << 3 | 00001000 | 8 |
| 1 << 4 | 00010000 | 16 |
| 1 << 5 | 00100000 | 32 |
| 1 << 6 | 01000000 | 64 |
| 1 << 7 | 10000000 | 128 |
Where bit shifts is used
A shift builds a mask for a single bit. The expression 1 << 5 gives the mask for bit 5.
A shift is faster than a multiplication on a small processor.
A driver combines a shift and a mask to place a field at the correct bit position.
Bit shifts: points to note
- A bit that moves past the bit width goes out of the register. The bit does not return on a shift back.
- A right shift of a signed value is not the same in every language. Some languages keep the top bit, others fill with 0.
- A shift by a number of positions equal to or larger than the bit width gives undefined behaviour in C.
The full bit editor
The full editor holds many values, evaluates expressions across them, and reads live values from a serial port.
Open this value in the full editorQuestions about bit shifts
- Is a left shift the same as a multiplication by two?
- Yes, until a bit moves past the bit width. The result is then incorrect, because the register drops the high bit.
- What is an arithmetic shift?
- An arithmetic right shift copies the top bit into the new high positions. This keeps the sign of a negative value.
- Why do drivers use 1 << n?
- The expression gives a value with only bit n set. This is the mask for that bit.