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
- The Bitwise Calculator
- A value to inspect (the Try it button loads
0b1100_1010)
Steps
Extract the low bits with AND
Set A to
0b1100_1010, the operation to AND, B to0x0Fand the width to 8-bit. The mask keeps only the low four bits, so the result is0000 1010, or 10.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.Switch a flag on with OR
Choose OR and set B to
0b0001. Bit 0 is turned on and every other bit is unchanged, giving1100 1011(203).Toggle a flag with XOR
Choose XOR with B as
0b1000_0000. The top bit flips from 1 to 0, giving0100 1010(74). Doing it again flips it back.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.
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.
~8is1111 0111in 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: