The Analogy: A Row of Light Switches
Every integer in C is really a row of light switches. An unsigned char is eight of them; a uint32_t is thirty-two. When you write 108, the hardware is holding 01101100 — six switches off, four on, in that exact order.
The operators you have used so far treat that row as a single number. Bitwise operators let you reach past the number and flip individual switches. That sounds like a party trick until you notice how much real software is built on it: file permissions, network protocol headers, pixel colours, hardware registers, compression formats, hash functions, and every flags parameter you have ever passed to an operating-system call.
The reason is efficiency of a very specific kind. Thirty-two independent yes-or-no facts fit in one uint32_t and can be tested in a single instruction. The same thirty-two facts stored as thirty-two bool variables would take thirty-two bytes and thirty-two comparisons.
Syntax or Core Structure
There are six bitwise operators. The first four work switch-by-switch; the last two slide the whole row sideways.
#include <stdio.h>
void print_bits(const char *label, unsigned char v) {
printf("%-10s ", label);
for (int i = 7; i >= 0; i--) {
putchar(((v >> i) & 1) ? '1' : '0');
}
printf(" (%3u)\n", v);
}
int main(void) {
unsigned char a = 0x6C; /* 0110 1100 */
unsigned char b = 0x3A; /* 0011 1010 */
print_bits("a", a);
print_bits("b", b);
print_bits("a & b", a & b); /* AND: on in both */
print_bits("a | b", a | b); /* OR: on in either */
print_bits("a ^ b", a ^ b); /* XOR: on in one only */
print_bits("~a", (unsigned char)~a); /* NOT: flip every bit */
print_bits("a << 1", (unsigned char)(a << 1)); /* shift left */
print_bits("a >> 2", a >> 2); /* shift right */
return 0;
}
Output:
a 01101100 (108)
b 00111010 ( 58)
a & b 00101000 ( 40)
a | b 01111110 (126)
a ^ b 01010110 ( 86)
~a 10010011 (147)
a << 1 11011000 (216)
a >> 2 00011011 ( 27)
Read the columns rather than the numbers. In the a & b row a bit is on only where both inputs had it on. In a ^ b a bit is on only where the inputs disagreed — and notice that 40 plus 86 is 126, because AND and XOR between them account for exactly the bits in OR.
The shifts are arithmetic in disguise: a << 1 doubled 108 to 216, and a >> 2 divided it by four to 27.
| Operator | Name | Bit is 1 in the result when | |
|---|---|---|---|
& | AND | both input bits are 1 | |
| `\ | ` | OR | at least one input bit is 1 |
^ | XOR | exactly one input bit is 1 | |
~ | NOT | the input bit was 0 | |
<< | left shift | a bit slid up from a lower position | |
>> | right shift | a bit slid down from a higher position |
Technical Depth: Masks, Shifts and the Rules That Bite
The four mask idioms
Almost all bit manipulation in production C is one of these five lines. Learn them as phrases, not as puzzles.
| Goal | Idiom | |
|---|---|---|
test bit n | if (value & (1u << n)) | |
set bit n | `value \ | = (1u << n);` |
clear bit n | value &= ~(1u << n); | |
toggle bit n | value ^= (1u << n); | |
keep the low n bits | value & ((1u << n) - 1) |
1u << n builds a mask with a single bit on. ~ turns that into a mask with a single bit off, which is why clearing needs both operators.
Precedence is genuinely surprising here
&, ^ and | all bind looser than == and !=. This is widely considered a mistake in C's design, and it is now permanent.
| Written | Actually parsed as | Almost certainly not what you meant | ||||||
|---|---|---|---|---|---|---|---|---|
value & MASK == 0 | value & (MASK == 0) | yes | ||||||
a + 1 << 2 | (a + 1) << 2 | usually fine, but check | ||||||
~a + 1 | (~a) + 1 | fine — this is two's complement negation | ||||||
| `x & 1 \ | \ | y & 1` | `(x & 1) \ | \ | (y & 1)` | fine, && and `\ | \ | ` are looser still |
Parenthesise every bitwise test: if ((value & MASK) == 0).
Three rules about shifting that are easy to break
- A shift count must be non-negative and smaller than the width of the promoted left operand.
x << 32on a 32-bit type is undefined behaviour, not zero. - Shift unsigned literals.
1 << 31overflows a signed 32-bitintand is undefined;1u << 31is correct. Get in the habit of writing1ualways. - Right-shifting a negative signed value is implementation-defined. Every mainstream compiler does an arithmetic shift, but the result is not integer division:
-7 >> 1is-4, while-7 / 2is-3. And-1 >> 1stays-1forever. Do bit work on unsigned types.
Integer promotion changes what ~ gives you
Operands narrower than int are promoted to int before any bitwise operator runs.
#include <stdio.h>
int main(void) {
unsigned char a = 0x6C; /* 108 */
printf("~a as int = %d\n", ~a);
printf("~a back in a byte = %u\n", (unsigned)(unsigned char)~a);
return 0;
}
Output:
~a as int = -109
~a back in a byte = 147
The bits you wanted are there, but 24 extra one-bits came along from the promotion. Cast back to the narrow type — or, better, use uint32_t from <stdint.h> and stop straddling widths.
Why XOR keeps appearing
x ^ x is 0, x ^ 0 is x, and x ^ y ^ y is x. That last identity — XOR is its own inverse — is the basis of parity bits, simple checksums, and the toggle idiom above.
It is also the basis of the famous XOR swap trick, which you should recognise and never write: it breaks when both arguments are the same variable, and it is slower than a temporary on every modern processor.
Real World Example: Packing a Colour and Carrying Permissions
Graphics code stores a pixel as one 32-bit integer with the channels stacked inside it. Shifting puts each channel in its lane; masking pulls it back out.
#include <stdio.h>
#include <stdint.h>
#define MAKE_RGB(r, g, b) ((((uint32_t)(r)) << 16) | (((uint32_t)(g)) << 8) | ((uint32_t)(b)))
#define RED(c) (((c) >> 16) & 0xFFu)
#define GREEN(c) (((c) >> 8) & 0xFFu)
#define BLUE(c) ( (c) & 0xFFu)
int main(void) {
uint32_t teal = MAKE_RGB(0, 128, 128);
printf("packed = 0x%06X\n", teal);
printf("r=%u g=%u b=%u\n", RED(teal), GREEN(teal), BLUE(teal));
/* Halve every channel: one shift each, no division needed. */
uint32_t dark = MAKE_RGB(RED(teal) >> 1, GREEN(teal) >> 1, BLUE(teal) >> 1);
printf("dark = 0x%06X\n", dark);
return 0;
}
Output:
packed = 0x008080
r=0 g=128 b=128
dark = 0x004040
The same technique carries a set of options in one argument, which is how chmod, open, fopen flags and most C APIs accept configuration:
#define PERM_READ (1u << 0) /* 0000 0001 */
#define PERM_WRITE (1u << 1) /* 0000 0010 */
#define PERM_EXEC (1u << 2) /* 0000 0100 */
unsigned perms = PERM_READ | PERM_WRITE; /* grant two */
if (perms & PERM_WRITE) { /* allowed to write */ }
perms &= ~PERM_WRITE; /* revoke just one */
perms ^= PERM_EXEC; /* toggle another */
Notice that granting, testing, revoking and toggling are each one operation on one variable, no matter how many flags exist. That is the whole appeal.
Common Mistakes
- Using
&where&&was meant, or|where||was meant. Both compile.2 && 1is 1, but2 & 1is 0, and the bitwise forms never short-circuit, so yourNULLguard stops guarding. - Forgetting parentheses around a bit test.
if (flags & MASK == 0)parses asif (flags & (MASK == 0)), which is almost always justflags & 0, which is always false. - Writing
1 << 31. On a 32-bit signedintthat overflows and is undefined behaviour. Write1u << 31. - Shifting by the width of the type or more.
x << 32on a 32-bit type is undefined behaviour, not zero, and different optimisation levels give different answers. - Clearing a bit with
&=and no~.value &= (1u << n)throws away every other bit and keeps only bitn. The correct form isvalue &= ~(1u << n). - Doing bit work on signed types. Right-shifting a negative value is implementation-defined, and the sign bit propagates in ways that surprise you. Use
unsignedoruint32_t. - Forgetting integer promotion around
~.~someUnsignedCharis anintwith 24 extra one-bits set. Cast the result back, or work inuint32_tthroughout. - Reaching for the XOR swap trick. It fails when both operands are the same variable, the one-line form
a ^= b ^= a ^= bis undefined behaviour, and a temporary variable is faster anyway.
Best Practices
- Do all bit manipulation on unsigned types, and prefer the fixed-width names from
<stdint.h>(uint8_t,uint32_t) whenever the exact layout matters. - Write
1u << n, never1 << n. Make it muscle memory. - Give every mask a name with
#defineor anenum. Bare hex constants in a condition are unreadable six months later. - In a mask macro, parenthesise every parameter and the whole body:
#define RED(c) (((c) >> 16) & 0xFFu). - When extracting a field, shift first and mask second:
(value >> 8) & 0xFFu. Masking first leaves the bits in the wrong place. - Always parenthesise a bitwise test against a comparison:
if ((flags & MASK) != 0). - Keep a
print_bitshelper in your debugging toolkit. Reading bit patterns beats reasoning about them. - Do not hand-convert arithmetic into shifts for speed. Write
n * 8andn / 4; every compiler already emits the shift, and your version breaks on negative values.
Practice Exercises
- A wider printer. Write
void print_bits32(uint32_t v)that prints all 32 bits with a space after every group of four, so0xDEADBEEFcomes out as1101 1110 1010 1101 1011 1110 1110 1111. - The four idioms as functions. Implement
bit_set,bit_clear,bit_toggleandbit_test, each taking auint32_tand a bit position. Start from0, set bits 0, 3 and 31, clear bit 3, toggle bit 0, and print the result in hexadecimal at each step. - Count the ones, twice. Write a population count that loops over all 32 positions, then write a second version using Kernighan's trick
while (v) { count++; v &= v - 1; }. Confirm both agree for0,1,0xFF,0xDEADBEEFand0xFFFFFFFF, and explain in one sentence why the second version loops once per set bit rather than 32 times. - Nibbles and mirrors. Write
uint8_t swap_nibbles(uint8_t b)so that0x4Cbecomes0xC4. Then writeuint8_t reverse_bits(uint8_t b)that mirrors all eight bits, and check that0b10110000becomes0b00001101. - A date in sixteen bits. Pack a date into a
uint16_tusing 7 bits for the years since 2000, 4 bits for the month and 5 bits for the day. Writepack_dateand three unpacking macros, verify the round trip for 29 August 2026, and state the latest year the format can represent.