Chapter 36Advanced

Bitmasks and Bit Manipulation

Work with individual bits! Set, clear, toggle, and check bits. Implement permission systems and flags efficiently.

18 min readUpdated 2024-12-16
bitmaskbitwiseflagspermissionsset bitclear bittoggle

What You Will Learn

  • βœ“Understand binary representation
  • βœ“Set, clear, and toggle individual bits
  • βœ“Check if a bit is set
  • βœ“Implement permission flags

01What are Bitmasks?

🎭 Simple Definition

A bitmask is a pattern of bits used to manipulate individual bits within a number. Each bit acts as an ON/OFF flag!

πŸ’‘ Why Use Bitmasks?

Memory Efficient

Store 8 flags in 1 byte!

Fast Operations

Bitwise ops are very fast

Permissions

Read, Write, Execute flags

Hardware Control

Control device registers

02Bitwise Operators Review

OperatorNameDescriptionExample
&AND1 if both bits are 15 & 3 = 1
|OR1 if either bit is 15 | 3 = 7
^XOR1 if bits are different5 ^ 3 = 6
~NOTFlip all bits~5 = -6
<<Left ShiftShift bits left5 << 1 = 10
>>Right ShiftShift bits right5 >> 1 = 2

03Common Bitmask Operations

OperationCodeDescription
Set bitx | (1 << n)Turn bit n ON
Clear bitx & ~(1 << n)Turn bit n OFF
Toggle bitx ^ (1 << n)Flip bit n
Check bit(x >> n) & 1Is bit n set?
bitmask_operations.c
C
1#include <stdio.h>
2
3// Helper function to print binary
4void printBinary(unsigned int n, int bits) {
5 for (int i = bits - 1; i >= 0; i--) {
6 printf("%d", (n >> i) & 1);
7 }
8}
9
10int main() {
11 unsigned int x = 0b00001010; // Start with 10
12
13 printf("Original: ");
14 printBinary(x, 8);
15 printf(" = %d\n", x);
16
17 // SET bit 0 (rightmost)
18 x = x | (1 << 0);
19 printf("Set bit 0: ");
20 printBinary(x, 8);
21 printf(" = %d\n", x);
22
23 // SET bit 4
24 x = x | (1 << 4);
25 printf("Set bit 4: ");
26 printBinary(x, 8);
27 printf(" = %d\n", x);
28
29 // CLEAR bit 1
30 x = x & ~(1 << 1);
31 printf("Clear bit 1: ");
32 printBinary(x, 8);
33 printf(" = %d\n", x);
34
35 // TOGGLE bit 3
36 x = x ^ (1 << 3);
37 printf("Toggle bit 3:");
38 printBinary(x, 8);
39 printf(" = %d\n", x);
40
41 // CHECK if bit 4 is set
42 if ((x >> 4) & 1) {
43 printf("Bit 4 is SET\n");
44 } else {
45 printf("Bit 4 is NOT set\n");
46 }
47
48 return 0;
49}
Output

Original: 00001010 = 10

Set bit 0: 00001011 = 11

Set bit 4: 00011011 = 27

Clear bit 1: 00011001 = 25

Toggle bit 3:00010001 = 17

Bit 4 is SET

04Practical Example: File Permissions

permissions.c
C
1#include <stdio.h>
2
3// Define permission flags using bit positions
4#define READ (1 << 0) // 001 = 1
5#define WRITE (1 << 1) // 010 = 2
6#define EXECUTE (1 << 2) // 100 = 4
7
8void printPermissions(int perms) {
9 printf("Permissions: ");
10 if (perms & READ) printf("Read ");
11 if (perms & WRITE) printf("Write ");
12 if (perms & EXECUTE) printf("Execute ");
13 printf("\n");
14}
15
16int main() {
17 int permissions = 0; // No permissions
18
19 printf("=== File Permission System ===\n\n");
20
21 // Grant READ permission
22 permissions |= READ;
23 printf("After granting READ:\n");
24 printPermissions(permissions);
25
26 // Grant WRITE permission
27 permissions |= WRITE;
28 printf("After granting WRITE:\n");
29 printPermissions(permissions);
30
31 // Grant EXECUTE permission
32 permissions |= EXECUTE;
33 printf("After granting EXECUTE:\n");
34 printPermissions(permissions);
35
36 // Revoke WRITE permission
37 permissions &= ~WRITE;
38 printf("After revoking WRITE:\n");
39 printPermissions(permissions);
40
41 // Check specific permission
42 if (permissions & EXECUTE) {
43 printf("\nUser CAN execute this file.\n");
44 }
45
46 if (!(permissions & WRITE)) {
47 printf("User CANNOT write to this file.\n");
48 }
49
50 // Grant multiple at once
51 int fullAccess = READ | WRITE | EXECUTE;
52 printf("\nFull access value: %d (binary: ", fullAccess);
53 for (int i = 2; i >= 0; i--) printf("%d", (fullAccess >> i) & 1);
54 printf(")\n");
55
56 return 0;
57}
Output

=== File Permission System ===

After granting READ:

Permissions: Read

After granting WRITE:

Permissions: Read Write

After granting EXECUTE:

Permissions: Read Write Execute

After revoking WRITE:

Permissions: Read Execute

User CAN execute this file.

User CANNOT write to this file.

Full access value: 7 (binary: 111)

05Practical Example: Game Flags

game_flags.c
C
1#include <stdio.h>
2
3// Game state flags
4#define HAS_SWORD (1 << 0) // 0001
5#define HAS_SHIELD (1 << 1) // 0010
6#define HAS_POTION (1 << 2) // 0100
7#define QUEST_COMPLETE (1 << 3) // 1000
8
9void printInventory(int flags) {
10 printf("Inventory: ");
11 if (flags & HAS_SWORD) printf("[Sword] ");
12 if (flags & HAS_SHIELD) printf("[Shield] ");
13 if (flags & HAS_POTION) printf("[Potion] ");
14 if (flags & QUEST_COMPLETE) printf("[Questβœ“] ");
15 if (flags == 0) printf("[Empty]");
16 printf("\n");
17}
18
19int main() {
20 int playerFlags = 0;
21
22 printf("=== Adventure Game ===\n\n");
23 printInventory(playerFlags);
24
25 // Pick up sword
26 printf("You found a SWORD!\n");
27 playerFlags |= HAS_SWORD;
28 printInventory(playerFlags);
29
30 // Pick up shield
31 printf("You found a SHIELD!\n");
32 playerFlags |= HAS_SHIELD;
33 printInventory(playerFlags);
34
35 // Use potion (can't - don't have one!)
36 if (playerFlags & HAS_POTION) {
37 printf("Used potion!\n");
38 playerFlags &= ~HAS_POTION;
39 } else {
40 printf("No potion to use!\n");
41 }
42
43 // Pick up potion
44 printf("You found a POTION!\n");
45 playerFlags |= HAS_POTION;
46 printInventory(playerFlags);
47
48 // Complete quest
49 printf("QUEST COMPLETE!\n");
50 playerFlags |= QUEST_COMPLETE;
51 printInventory(playerFlags);
52
53 // Check if ready for boss (need sword AND shield)
54 if ((playerFlags & HAS_SWORD) && (playerFlags & HAS_SHIELD)) {
55 printf("\nYou are ready to fight the boss!\n");
56 }
57
58 return 0;
59}
Output

=== Adventure Game ===

Inventory: [Empty]

You found a SWORD!

Inventory: [Sword]

You found a SHIELD!

Inventory: [Sword] [Shield]

No potion to use!

You found a POTION!

Inventory: [Sword] [Shield] [Potion]

QUEST COMPLETE!

Inventory: [Sword] [Shield] [Potion] [Questβœ“]

You are ready to fight the boss!

06Summary

🎯 Key Takeaways

  • β€’Bitmask: Pattern of bits as flags
  • β€’Set bit: x | (1 << n)
  • β€’Clear bit: x & ~(1 << n)
  • β€’Toggle bit: x ^ (1 << n)
  • β€’Check bit: (x >> n) & 1
  • β€’Use cases: Permissions, flags, hardware, games

πŸŽ‰Congratulations!

You've completed all the C programming tutorials! Explore more topics or start building projects: