A bitwise operator combines or transforms corresponding bits of integer operands. Treating each bit as a truth value makes & resemble logical AND and | resemble logical OR, but bitwise operators process all bits without short-circuit evaluation. section 5.7.2
Representing flock membership
Assign one power-of-two constant to each corvid: FLOCK_MAGPIE = 1U, FLOCK_RAVEN = 2U, FLOCK_JAY = 4U, and FLOCK_CHOUGH = 8U. Start with unsigned flock = FLOCK_EMPTY; add a jay with flock |= FLOCK_JAY; test for a chough with if (flock & FLOCK_CHOUGH) do_something_chough_specific(flock);. Each membership occupies one bit, so |= sets a membership bit and & tests it. TAKEAWAY: Use distinct power-of-two flags when one integer must represent several independent memberships. section 5.7.2
The principal bitwise forms correspond to set operations:
- & combines bits with AND and represents intersection; | combines them with OR and represents union; ^ keeps bits set in exactly one operand; ~ complements each bit. section 5.7.2
- Do not substitute && for &, or || for |: && and || perform logical operations and use short-circuit evaluation, while bitwise operators do not. section 5.7.2
- For unsigned values, negation can be constructed as -A = ~A + 1; signed two’s-complement types use the same bit operation while interpreting a high-order one bit as negative. section 5.7.5
Table 5.5. Effects of bitwise operators (view table figure)
| Value |
Hex |
b15 |
... |
b0 |
Set op |
Set |
|
|---|---|---|---|---|---|---|---|
| V | 65535 | 0xFFFF | 1111111111111111 | {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} | |||
| A | 240 | 0x00F0 | 0000000011110000 | {4, 5, 6, 7} | |||
| ~A | 65295 | 0xFF0F | 1111111100001111 | V \ A | {0, 1, 2, 3, 8, 9, 10, 11, 12, 13, 14, 15} | ||
| -A | 65296 | 0xFF10 | 1111111100010000 | {4, 8, 9, 10, 11, 12, 13, 14, 15} | |||
| B | 287 | 0x011F | 0000000100011111 | {0, 1, 2, 3, 4, 8} | |||
| A|B | 511 | 0x01FF | 0000000111111111 | A ∪ B | {0, 1, 2, 3, 4, 5, 6, 7, 8} | ||
| A&B | 16 | 0x0010 | 0000000000010000 | A ∩ B | {4} | ||
| A^B | 495 | 0x01EF | 0000000111101111 | AΔB | {0, 1, 2, 3, 5, 6, 7, 8} | ||
Compare decimal values, hexadecimal forms, binary bit patterns, and corresponding set operations for ~, -, |, &, and ^. section 5.7.2
Bit patterns do not remove signed-arithmetic hazards. Unsigned overflow wraps around, whereas signed overflow is undefined and can let a compiler transform apparently terminating code into an infinite loop. section 5.7.5





