Beetwise

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 it

The value 10110110 before you apply the mask. Select a bit to change it. Change the bit width or the signed mode to see the effect.

Name or expression
ID0
Binary
0b
Hex
0x
Decimal
ASCII
·
Shift
Sign
Bits
Endian
7
6
5
4
3
2
1
0

Worked example

Keep the lowest four bits of 10110110:

  1. Write the mask for the lowest four bits: 00001111, which is 0x0F.
  2. Apply AND between the value and the mask.
  3. Every bit of the mask that is 0 clears the bit in the result.
  4. The result is 00000110, which is 6.

Where this 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.

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 tool

The full editor holds many values at the same time. It also evaluates expressions across them, and it reads live values from a serial port.

Open the full editor

Questions

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.