Bit mask calculator
A bit mask is a value that selects the bits you act on.
The mask for bit n is 1 shifted left by n positions.
Four operations cover the work: set, clear, toggle and read.
Try a bit mask in the bit editor
A mask for bit 3 and bit 5, which is 0x28. Edit the expression or select a bit to flip it.
7
6
5
4
3
2
1
0
0x28
hex · 8 bits
- binary
- 0b00101000
- value
- 40
Bit width
Shift
A bit mask step by step
Build a mask for bit 3 and bit 5:
- The mask for bit 3 is 1 << 3, which is 0x08.
- The mask for bit 5 is 1 << 5, which is 0x20.
- Combine the two with OR: 0x08 | 0x20 gives 0x28.
- The value 0x28 has the value 1 at bit 3 and at bit 5, and 0 everywhere else.
The four mask operations, with the C idiom for each
| Operation | C idiom | Effect on the register |
|---|---|---|
| Set | reg |= mask | The bits of the mask take the value 1 |
| Clear | reg &= ~mask | The bits of the mask take the value 0 |
| Toggle | reg ^= mask | The bits of the mask change to the other value |
| Read | (reg & mask) != 0 | True when any bit of the mask has the value 1 |
| Read a field | (reg & mask) >> shift | The field moves down to bit 0 |
| Mask for bit n | 1u << n | One bit, at the position n |
| Mask for a field | ((1u << width) - 1) << shift | A run of bits, at the position shift |
Where a bit mask is used
A driver writes one field of a register and leaves the other fields alone.
A flag word holds many boolean values in one integer, one bit for each.
A protocol frame packs several small fields into one byte.
A bit mask: points to note
- Write 1u << n rather than 1 << n. The literal 1 is a signed int, and a shift by 31 overflows it.
- A clear needs the NOT of the mask, not the mask. The idiom is reg &= ~mask.
- A read of a field needs a shift after the AND, or the value stays at its own position.
- A read, a change and a write are three steps. An interrupt between them loses the change.
- The export dialog of the full editor writes the mask as a C define or a constexpr.
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 a bit mask
- What is a bit mask?
- A bit mask is a value whose bits mark the positions you act on. The other positions hold 0.
- How do I set one bit and keep the others?
- Apply OR between the register and the mask: reg |= mask. OR never clears a bit.
- How do I clear one bit?
- Apply AND between the register and the NOT of the mask: reg &= ~mask.
- How do I read a field of several bits?
- Apply AND with the mask, then shift the result down: (reg & mask) >> shift.