Module 9 · Bitwise Operations, Common Errors and Applications — topic 1 of 3
Bitwise Operations
&, |, ^, ~, << and >> operate on the individual bits of integers. Learn masks for setting, clearing, toggling and testing bits, shifts as fast multiplication, and the rules that keep bit code portable.
Learning objectives
- Evaluate &, |, ^, ~, << and >> by hand in binary
- Set, clear, toggle and test bits with masks
- Use unsigned types to keep shifts well defined
Definition
Bitwise operators act on the binary representation of integer operands:&(AND),|(OR),^(exclusive OR) and~(complement) combine or invert corresponding bits;<<and>>shift bits left or right by a given number of positions.
Introduction
Hardware registers, file permissions, network headers and compact flag sets all store information in individual bits. Bitwise operators let C manipulate those bits directly and efficiently.
To read bitwise code, think in binary. 12 is 1100, 10 is 1010; 12 & 10 keeps only the bits set in both: 1000, which is 8.
Why it matters
Embedded and systems programming relies on bit manipulation every day, and bit tricks (power-of-two checks, counting set bits, swapping with XOR) are favourite interview questions.
Packing several boolean flags into one integer saves memory and makes functions such as fopen-style option flags possible.
Detailed explanation
Masks: 1u << n has only bit n set. Then: set bit n with x |= 1u << n; clear it with x &= ~(1u << n); toggle it with x ^= 1u << n; test it with (x >> n) & 1u or x & (1u << n).
Shifting left by n multiplies by 2ⁿ and shifting an unsigned value right by n divides by 2ⁿ (rounding down), as long as no bits overflow.
Portability rules: shifting by a negative amount or by at least the type's width is undefined. Left-shifting a negative signed value, or into the sign bit, is undefined; right-shifting a negative signed value is implementation-defined. Use unsigned types for bit manipulation.
Bitwise & and | are not the same as logical && and ||: they don't short-circuit and they operate on every bit. Note also that &, ^ and | have lower precedence than ==, so write (x & MASK) == 0 with parentheses.
Syntax
- Bits are numbered from 0 at the least significant (rightmost) end.
- Use
1u(unsigned) when building masks. - Parenthesise bitwise expressions inside comparisons.
Code examples
The six operators
a&b=8 a|b=14 a^b=6 a<<2=48 a>>1=6 ~a & 0xF = 3
Printing bits
00000101 11001000 01010000
More examples
Permission flags and classic bit tricks
rw- rwx r-x has write? no 64 power of two? 1, 96? 0 set bits in 255: 8, in 1024: 1 x=3 y=7
Step-by-step explanation
- Each permission is a distinct bit, so they combine with
|without interfering. p |= PERM_EXECsets bit 2;p &= ~PERM_WRITEclears bit 1 while keeping the others.- A power of two has exactly one set bit, so
x & (x - 1)clears it and leaves 0. x &= x - 1removes the lowest set bit each iteration, so the loop runs once per set bit (Kernighan's method).- The XOR swap works for distinct variables but is slower and less clear than a temporary; it is shown only because interviews ask about it.
Expected output
Running “Permission flags and classic bit tricks” prints exactly:
Practical applications
- Unix file permissions (rwx for user, group, others) are bit flags.
- Microcontroller code sets register bits to configure pins and timers.
- Compression, cryptography and checksums (CRC) are built from shifts and XOR.
Best practices
- Use unsigned integer types for flags and masks.
- Name masks with constants or enums rather than raw hex numbers.
- Always parenthesise bitwise sub-expressions.
Common mistakes
Precedence of & versus ==
Avoid
Prefer
== binds tighter, so this computes flags & (MASK == 0).
Shifting a signed 1 into the sign bit
Avoid
Prefer
With a 32-bit int, 1 << 31 overflows into the sign bit — undefined behaviour. Unsigned shifts are well defined.
Important notes
- Shift amounts must be less than the width of the promoted left operand;
x << 32for a 32-bitunsignedis undefined, not zero. - C23 adds
<stdbit.h>with functions such asstdc_count_onesfor counting bits portably.
Key takeaways
&masks,|sets,^toggles,~inverts, shifts multiply/divide by powers of two.- Set/clear/toggle/test bit n with
1u << nmasks. - Use unsigned types and parenthesise bitwise expressions.
Try it yourself
- 1Write
unsigned reverse_bits(unsigned char v)that reverses the 8 bits of a byte. - 2Store 8 boolean settings in one
unsigned charand write functions to turn each setting on, off and check it.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
7 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- ModerateWhat is printed?
- ModerateWhat is printed?