C Bitwise Operations Cheat Sheet
Summarizes C's bitwise operators, bitmask flag patterns, and common bit manipulation tricks like counting set bits and power-of-two checks.
1 PageIntermediateApr 10, 2026
Bitwise Operators
The core AND, OR, XOR, NOT, and shift operators.
c
unsigned int a = 0xA; // 1010 in binary (10)unsigned int b = 0x6; // 0110 in binary (6)unsigned int and_result = a & b; // 0010 = 2 (AND)unsigned int or_result = a | b; // 1110 = 14 (OR)unsigned int xor_result = a ^ b; // 1100 = 12 (XOR)unsigned int not_result = ~a; // Flips all bits (bitwise NOT)unsigned int left_shift = a << 2; // 101000 = 40 (multiply by 4)unsigned int right_shift = a >> 1; // 0101 = 5 (divide by 2)
Flags with Bitmasks
Packing multiple boolean flags into one integer.
c
#define FLAG_READ (1 << 0) // 0001#define FLAG_WRITE (1 << 1) // 0010#define FLAG_EXECUTE (1 << 2) // 0100unsigned int perms = FLAG_READ | FLAG_WRITE; // Set multiple flags: 0011perms |= FLAG_EXECUTE; // Set a flagperms &= ~FLAG_WRITE; // Clear a flagint has_read = (perms & FLAG_READ) != 0; // Test a flagperms ^= FLAG_READ; // Toggle a flag
Common Bit Tricks
Idioms for fast, allocation-free integer operations.
c
int is_even = (n & 1) == 0; // Check even/odd without %int is_power_of_two = n > 0 && (n & (n - 1)) == 0; // Power-of-two checkint x = 3, y = 5;x ^= y; y ^= x; x ^= y; // Swap without a temp variable (XOR swap)unsigned int count_set_bits(unsigned int v) { int count = 0; while (v) { v &= (v - 1); // Clears the lowest set bit each iteration count++; } return count; // Brian Kernighan's algorithm}
Operators & Rules
What each operator does and where the sharp edges are.
- & (AND)- Result bit is 1 only if both operand bits are 1; used for masking/testing bits
- | (OR)- Result bit is 1 if either operand bit is 1; used for setting bits
- ^ (XOR)- Result bit is 1 if the operand bits differ; used for toggling bits
- ~ (NOT)- Unary operator that inverts every bit; result depends on the operand's bit width
- << / >>- Shift bits left/right; left-shifting into or past the sign bit of a signed int is undefined behavior
- Signed right shift- Implementation-defined for negative numbers (may be arithmetic or logical)
- Unsigned types- Prefer unsigned int for bitmask work to avoid sign-related undefined behavior
Pro Tip
Left-shifting a signed int far enough to set or overflow the sign bit is undefined behavior in C — use unsigned types for bit manipulation and masks.
Was this cheat sheet helpful?
Explore Topics
#CBitwiseOperations#CBitwiseOperationsCheatSheet#Programming#Intermediate#BitwiseOperators#FlagsWithBitmasks#CommonBitTricks#OperatorsRules#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance