Bitwise Operators Explained: AND, OR, XOR, NAND, NOR and XNOR
A practical guide to bitwise operations with truth tables, worked examples and real uses such as flags, masks and toggles.
What Bitwise Means
A bitwise operation compares two numbers one bit at a time. Take 12 (1100) and 10 (1010):
| Operation | Result (binary) | Decimal |
|---|---|---|
| 12 AND 10 | 1000 | 8 |
| 12 OR 10 | 1110 | 14 |
| 12 XOR 10 | 0110 | 6 |
Check any pair with the [Bitwise Calculator](/tools/bitwise-calculator).
The Six Operations
- AND is 1 only when both bits are 1. Use it to test or clear flags. [AND Calculator](/tools/and-calculator)
- OR is 1 when either bit is 1. Use it to set flags. [OR Calculator](/tools/or-calculator)
- XOR is 1 when the bits differ. Use it to toggle bits and in checksums. [XOR Calculator](/tools/xor-calculator)
- NAND is NOT AND. Every logic circuit can be built from NAND gates alone. [NAND Calculator](/tools/nand-calculator)
- NOR is NOT OR. [NOR Calculator](/tools/nor-calculator)
- XNOR is NOT XOR, so it is 1 when the bits are equal. [XNOR Calculator](/tools/xnor-calculator)
Why Bit Width Matters
NOT-style operations flip every bit, including leading zeros. In 8 bits, NOT 0 is 255. In 32 bits it is 4,294,967,295, which is -1 as a signed integer. Always pick the width your language or hardware uses.
Real Uses
- Permission flags: READ = 1, WRITE = 2, EXEC = 4. A user with READ and WRITE has 3 (1 OR 2). Check WRITE with 3 AND 2.
- Masks: IP subnet masks are AND operations on addresses.
- Fast toggles: x XOR 1 flips the lowest bit.
- Shifts: 1 << 4 is 16, a quick way to build flag values.
Summary
Bitwise operators work on individual bits and are the basis of flags, masks, checksums and digital logic. Use a calculator to verify your truth tables and widths before shipping low-level code.
Try our free tools
Put these tips into practice with 45+ free online tools - no signup, no login.
Browse Free Tools