Index
Practicle Usecases of Bitwise Operators
Flags and Bit Masks
Bitwise operators are often used for managing multiple boolean flags within a single integer variable. This allows for efficient storage and manipulation of state information.
Example: Suppose you’re developing a game where each player can have multiple abilities (e.g., speed boost, invisibility, and double jump). Instead of using separate boolean variables for each ability, you can use a single integer as a bitmask.
#include <stdio.h>
#define SPEED_BOOST (1 << 0) // 0001
#define INVISIBILITY (1 << 1) // 0010
#define DOUBLE_JUMP (1 << 2) // 0100
int main() {
int playerAbilities = 0; // All abilities off
// Enable abilities
playerAbilities |= SPEED_BOOST; // 0001
playerAbilities |= INVISIBILITY; // 0011
// Check if player has double jump
if (playerAbilities & DOUBLE_JUMP) {
printf("Player can double jump!\n");
} else {
printf("Player cannot double jump.\n");
}
// Disable speed boost
playerAbilities &= ~SPEED_BOOST; // 0010
return 0;
}
Swapping Values Without Temporary Variable
Using bitwise XOR, you can swap two variables without using a temporary variable. This can save memory in low-level programming, although modern compilers typically optimize this.
#include <stdio.h>
int main() {
int x = 5; // 0101
int y = 3; // 0011
printf("Before Swap: x = %d, y = %d\n", x, y);
x = x ^ y; // x now becomes 6 (0110)
y = x ^ y; // y becomes 5 (0101)
x = x ^ y; // x becomes 3 (0011)
printf("After Swap: x = %d, y = %d\n", x, y);
return 0;
}
Efficient Multiplication and Division by Powers of Two
You can multiply or divide integers by powers of two using bit shifts, which are generally faster than using multiplication or division operators.
Example:
#include <stdio.h>
int main() {
int num = 8;
// Multiply by 4 (2^2)
int multiplied = num << 2; // 8 * 4 = 32
printf("%d multiplied by 4 is: %d\n", num, multiplied);
// Divide by 4 (2^2)
int divided = num >> 2; // 8 / 4 = 2
printf("%d divided by 4 is: %d\n", num, divided);
return 0;
}