Bitwise Operators in C

Bitwise operators work directly on the **bits** (0s and 1s) of integers. They are extremely fast and widely used in low-level programming, embedded systems, graphics, cryptography, and optimization.

Operate on **integer types** only (char, short, int, long, etc.)
Very fast (single CPU instruction)
Common in flags, masks, bit fields, packing/unpacking data

All 6 Bitwise Operators in C

OperatorSymbolDescriptionCommon Use Cases
Bitwise AND&1 only if both bits are 1Clear bits, check flags, masks
Bitwise OR|1 if at least one bit is 1Set bits, combine flags
Bitwise XOR^1 if bits are differentToggle bits, find unique, swap without temp
Bitwise NOT~Flip all bits (1→0, 0→1)One’s complement, invert mask
Left Shift<<Shift bits left (multiply by 2ⁿ)Fast multiply, bit packing
Right Shift>>Shift bits right (divide by 2ⁿ)Fast divide, extract bits

Truth Tables (AND, OR, XOR)

ABA & BA | BA ^ B
00000
01011
10011
11110
Note: ~A (NOT) is simply the opposite of A

Practical Examples & Tricks

1. Check if number is even/odd

C
if (n & 1)   // odd
    printf("Odd");
else         // even
    printf("Even");

2. Set, Clear, Toggle, Check a bit

C
// Set bit at position pos (0-based)
n |= (1 << pos);

// Clear bit
n &= ~(1 << pos);

// Toggle bit
n ^= (1 << pos);

// Check if bit is set
if (n & (1 << pos)) printf("Bit is ON");

3. Swap two numbers without temporary variable

C
a = a ^ b;
b = a ^ b;
a = a ^ b;

4. Fast multiply & divide by power of 2

C
x << 3    // x * 8
x >> 2    // x / 4

5. Extract lower/upper nibble

C
lower_nibble = n & 0x0F;
upper_nibble = (n >> 4) & 0x0F;

Useful Bit Masks (Hex)

MaskHexBinary
0xFF11111111Last 8 bits (1 byte)
0x0F00001111Lower nibble
0xF011110000Upper nibble
0x0100000001Check LSB (odd/even)
0x800000001000...0Check sign bit (32-bit)

Important Notes & Warnings

  • Right shift (>>) on signed integers is implementation-defined (arithmetic vs logical)
  • Use unsigned types when doing bit manipulation for predictable behavior
  • ~ operator flips all bits (including higher bits) → careful with signed integers
  • Always use parentheses with shifts: `(1 << pos)`