How to use a bit mask
A mask is a value that selects one or more bits.
Use AND with a mask to test bits. Use OR with a mask to set bits. Use XOR with a mask to flip bits.
To clear bits, use AND with the inverted mask.
Try bit masks in the bit editor
The result of 0xB6 AND the mask 0x0F. Edit the expression or select a bit to flip it.
7
6
5
4
3
2
1
0
0x06
hex · 8 bits
- value
- 6
Shift
Bit masks step by step
Keep the lowest four bits of 10110110:
- Write the mask for the lowest four bits: 00001111, which is 0x0F.
- Apply AND between the value and the mask.
- Every bit of the mask that is 0 clears the bit in the result.
- The result is 00000110, which is 6.
Masks in common use
| Mask | Binary | Purpose |
|---|---|---|
| 0x01 | 00000001 | Test bit 0 |
| 0x0F | 00001111 | Keep the low nibble |
| 0xF0 | 11110000 | Keep the high nibble |
| 0x7F | 01111111 | Clear the top bit |
| 0x80 | 10000000 | Test the top bit |
| 0xFF | 11111111 | Keep the low byte |
| 0xFFFF | 16 bits set | Keep the low two bytes |
Where bit masks is used
A hardware register packs several fields into one value.
A mask extracts one field without a change to the other fields.
A driver reads a register, applies a mask, and then writes the register back.
Bit masks: points to note
- AND with the mask keeps the selected bits. AND with the inverted mask clears them.
- A mask of 0xFF selects one byte. A mask of 0xFFFF selects two bytes.
- Set the correct bit width before you invert a mask. An inverted 8-bit mask differs from an inverted 32-bit mask.
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 masks
- How do I test one bit?
- Apply AND between the value and a mask that has only that bit set. A result of 0 means the bit is clear.
- How do I set one bit?
- Apply OR between the value and a mask that has only that bit set. The other bits do not change.
- How do I clear one bit?
- Invert the mask, then apply AND. In C this is value &= ~mask.