Skip to content

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.

Beginner 16 min read·Lesson 35 of 37 in C Programming

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

OperatorNameExample (binary)Result
a & bAND1100 & 10101000 (8)
a | bOR1100 | 10101110 (14)
a ^ bXOR1100 ^ 10100110 (6)
~aNOT~00001100 (8-bit)11110011
a << 2left shift0011 << 21100 (12)
a >> 1right shift1100 >> 10110 (6)

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

C
unsigned flags = 0;
flags |= 1u << 3; /* set bit 3 */
flags &= ~(1u << 3); /* clear bit 3 */
flags ^= 1u << 0; /* toggle bit 0 */
int on = (flags >> 2) & 1u; /* test bit 2 */
unsigned times8 = x << 3; /* x * 8 */
  • 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

C
#include <stdio.h>
int main(void) {
unsigned a = 12, b = 10; /* 1100, 1010 */
printf("a&b=%u a|b=%u a^b=%u\n", a & b, a | b, a ^ b);
printf("a<<2=%u a>>1=%u\n", a << 2, a >> 1);
printf("~a & 0xF = %u\n", ~a & 0xFu);
return 0;
}
Output
a&b=8 a|b=14 a^b=6
a<<2=48 a>>1=6
~a & 0xF = 3

Printing bits

C
#include <stdio.h>
void print_bits(unsigned char v) {
for (int i = 7; i >= 0; i--)
putchar((v >> i) & 1u ? '1' : '0');
putchar('\n');
}
int main(void) {
print_bits(5);
print_bits(200);
print_bits((unsigned char)(5 << 4));
return 0;
}
Output
00000101
11001000
01010000

More examples

Permission flags and classic bit tricks

C
#include <stdio.h>
enum { PERM_READ = 1u << 0, PERM_WRITE = 1u << 1, PERM_EXEC = 1u << 2 };
void show(unsigned p) {
printf("%c%c%c\n", p & PERM_READ ? 'r' : '-', p & PERM_WRITE ? 'w' : '-', p & PERM_EXEC ? 'x' : '-');
}
int is_power_of_two(unsigned x) { return x != 0 && (x & (x - 1)) == 0; }
int count_set_bits(unsigned x) {
int n = 0;
while (x) { x &= x - 1; n++; } /* clears the lowest set bit */
return n;
}
int main(void) {
unsigned p = PERM_READ | PERM_WRITE;
show(p);
p |= PERM_EXEC;
show(p);
p &= ~PERM_WRITE;
show(p);
printf("has write? %s\n", (p & PERM_WRITE) ? "yes" : "no");
printf("64 power of two? %d, 96? %d\n", is_power_of_two(64), is_power_of_two(96));
printf("set bits in 255: %d, in 1024: %d\n", count_set_bits(255), count_set_bits(1024));
int x = 7, y = 3;
x ^= y; y ^= x; x ^= y; /* XOR swap (curiosity) */
printf("x=%d y=%d\n", x, y);
return 0;
}
Output
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_EXEC sets bit 2; p &= ~PERM_WRITE clears 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 - 1 removes 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:

TextOutput
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

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

if (flags & MASK == 0) { /* ... */ }

Prefer

if ((flags & MASK) == 0) { /* ... */ }

== binds tighter, so this computes flags & (MASK == 0).

Shifting a signed 1 into the sign bit

Avoid

int mask = 1 << 31;

Prefer

unsigned mask = 1u << 31;

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 << 32 for a 32-bit unsigned is undefined, not zero.
  • C23 adds <stdbit.h> with functions such as stdc_count_ones for counting bits portably.

Key takeaways

  • & masks, | sets, ^ toggles, ~ inverts, shifts multiply/divide by powers of two.
  • Set/clear/toggle/test bit n with 1u << n masks.
  • Use unsigned types and parenthesise bitwise expressions.

Try it yourself

  1. 1
    Write unsigned reverse_bits(unsigned char v) that reverses the 8 bits of a byte.
  2. 2
    Store 8 boolean settings in one unsigned char and 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?
Practise this topic