What are the bitwise operators in C?
Short answer: C has six bitwise operators: AND &, OR |, XOR ^, NOT ~, left shift << and right shift >>. They work on each bit independently, unlike the logical operators &&, || and !, which treat the whole value as true or false.
| Operator | Name | Rule per bit | Example (a=0b1100, b=0b1010) |
|---|---|---|---|
& |
AND | 1 only if both bits are 1 | a & b = 0b1000 |
| | | OR | 1 if either bit is 1 | a | b = 0b1110 |
^ |
XOR | 1 if the bits differ | a ^ b = 0b0110 |
~ |
NOT | flips every bit | ~a = all bits inverted |
<< |
left shift | moves bits up, fills with 0 | a << 1 = 0b11000 |
>> |
right shift | moves bits down | a >> 2 = 0b0011 |
What each one is used for in firmware
&tests or clears bits:if (reg & BIT3),reg &= ~BIT3.|sets bits:reg |= BIT3.^toggles bits:led ^= BIT5.~builds inverted masks for clearing.<< nmultiplies by 2ⁿ and builds single-bit masks:1u << n.>> ndivides by 2ⁿ (for unsigned values) and extracts fields.
Logical vs bitwise: 0x10 && 0x01 is 1 (both non-zero), but 0x10 & 0x01 is 0. Logical operators also short-circuit: in p && p->x the right side is not evaluated when p is NULL. Bitwise operators always evaluate both sides.
Precedence trap: &, ^ and | bind more loosely than ==. if (reg & MASK == MASK) parses as reg & (MASK == MASK), i.e. reg & 1. Always write if ((reg & MASK) == MASK).
Follow-up: "Why use 1u instead of 1?" Because 1 << 31 shifts into the sign bit of a signed int, which is undefined behaviour before C23. 1u << 31 is well-defined.