C Language
12. Bitwise Operations & MasksIntermediate10 min read

Bitwise Operators, Bit Manipulation & Masks in C

Manipulate individual memory bits: AND (&), OR (|), XOR (^), NOT (~), Left Shift (<<), Right Shift (>>), and building bit-flags.

Key Takeaways & Core Concepts
  • Bitwise operations operate directly on binary representations of integer types.
  • Setting a bit: number |= (1 << n);
  • Clearing a bit: number &= ~(1 << n);
  • Toggling a bit: number ^= (1 << n);
  • Checking a bit: (number & (1 << n)) != 0;
  • Left shift (x << n) multiplies by 2^n; right shift (x >> n) divides by 2^n.

Bitwise Operators & Bitmasking Fundamentals

In systems programming, hardware drivers, and network protocols, data is packed into single bits to minimize memory transmission overhead.

  • AND (`&`): Clears bits. Evaluates to 1 only if both bits are 1.
  • OR (`|`): Sets bits. Evaluates to 1 if either bit is 1.
  • XOR (`^`): Flips bits. Evaluates to 1 if bits differ.
  • NOT (`~`): Inverts all bits.
  • Left Shift (`<<`): Shifts bits to the left, padding zeros on the right.
  • Right Shift (`>>`): Shifts bits to the right.
Practical Bitmasking Toolkit
1#include <stdio.h>
2
3#define SET_BIT(num, pos) ((num) |= (1U << (pos)))
4#define CLEAR_BIT(num, pos) ((num) &= ~(1U << (pos)))
5#define TOGGLE_BIT(num, pos) ((num) ^= (1U << (pos)))
6#define CHECK_BIT(num, pos) (((num) >> (pos)) & 1U)
7
8int main(void) {
9 unsigned char byte = 0b00000000;
10
11 SET_BIT(byte, 3); // Turn on 3rd bit -> 00001000 = 8
12 printf("After setting bit 3: 0x%02X (decimal %d)\n", byte, byte);
13
14 TOGGLE_BIT(byte, 0); // Turn on 0th bit -> 00001001 = 9
15 printf("After toggling bit 0: 0x%02X (decimal %d)\n", byte, byte);
16
17 printf("Is bit 3 active? %s\n", CHECK_BIT(byte, 3) ? "YES" : "NO");
18 printf("Is bit 2 active? %s\n", CHECK_BIT(byte, 2) ? "YES" : "NO");
19
20 CLEAR_BIT(byte, 3); // Turn off 3rd bit -> 00000001 = 1
21 printf("After clearing bit 3: 0x%02X (decimal %d)\n", byte, byte);
22
23 return 0;
24}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
24 lines
Note: Bitmasking macros are fundamental building blocks in embedded firmware and operating system flags.
Practice & AssessmentC Programming Complete Course

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 1 correct(0 attempted)

1

Which bitwise expression checks if the 4th bit (0-indexed) of variable x is set?

Intermediate