Bitwise Calculator · Tutorial

How to test and set flags with a bitmask

6 min readintermediateUpdated

Many APIs and file formats store several on/off options in one number. This tutorial shows how to read the low four bits of a value with AND, switch a flag on with OR, and flip one with XOR, watching each result bit by bit.

What you need

Steps

  1. Extract the low bits with AND

    Set A to 0b1100_1010, the operation to AND, B to 0x0F and the width to 8-bit. The mask keeps only the low four bits, so the result is 0000 1010, or 10.

  2. Test a single flag

    To check bit 3 (value 8), change B to 0b1000. A non-zero result (8) means the flag is set. Zero would mean it's off.

  3. Switch a flag on with OR

    Choose OR and set B to 0b0001. Bit 0 is turned on and every other bit is unchanged, giving 1100 1011 (203).

  4. Toggle a flag with XOR

    Choose XOR with B as 0b1000_0000. The top bit flips from 1 to 0, giving 0100 1010 (74). Doing it again flips it back.

  5. Clear a flag

    To turn a flag off, AND with the inverted mask. For bit 3 in 8 bits, use B = 0b1111_0111.

Try it yourself

Opens the Bitwise Calculator with this tutorial's sample loaded.

Try it now

Common mistakes

Using the flag's position instead of its value
Bit 3 has the value 8 (1 << 3), not 3. Use Shift left with A = 1 and B = 3 to get the mask.
Forgetting the width
Inverted masks depend on the width. ~8 is 1111 0111 in 8 bits but has many more ones in 32 bits.
Comparing with == 1
AND with bit 3 gives 8, not 1. Test for "not zero" instead.

Next steps

Go back to the Bitwise Calculator, or keep going with one of these: