C Bitwise Operators – Direct Manipulation of Bits

Bitwise operators in C allow you to manipulate individual bits of data directly. They’re especially useful in systems programming, embedded systems, game development, and performance-critical applications.

Why Use Bitwise Operators?

Bitwise operators:

  • Perform operations faster than arithmetic.

  • Help in flags, masks, compression, and encryption.

  • Give low-level control over data and memory.

List of Bitwise Operators in C

OperatorNameDescription
&ANDSets each bit to 1 if both bits are 1
``OR
^XORSets each bit to 1 if only one is 1
~NOTInverts all the bits
<<Left ShiftShifts bits left, filling with 0 on the right
>>Right ShiftShifts bits right, preserving sign on left

Bitwise AND (&)

int a = 5;  // 0101
int b = 3;  // 0011
int result = a & b; // 0001 → 1

Bitwise OR (|)

int a = 5;  // 0101
int b = 3;  // 0011
int result = a | b; // 0111 → 7

Bitwise NOT (~)

int a = 5;  // 0101
int result = ~a; // 1010 → -6 (in 2's complement for 4 bits)

Left Shift (<<)

int a = 3;  // 0011
int result = a << 2; // 1100 → 12

Right Shift (>>)

int a = 12; // 1100
int result = a >> 2; // 0011 → 3

Complete Code Example

#include <stdio.h>

int main() {
    int a = 5, b = 3;

    printf("a & b = %d\n", a & b);  // AND
    printf("a | b = %d\n", a | b);  // OR
    printf("a ^ b = %d\n", a ^ b);  // XOR
    printf("~a = %d\n", ~a);        // NOT
    printf("a << 1 = %d\n", a << 1); // Left Shift
    printf("a >> 1 = %d\n", a >> 1); // Right Shift

    return 0;
}

 Output:

a & b = 1
a | b = 7
a ^ b = 6
~a = -6
a << 1 = 10
a >> 1
= 2

Best Practices

TipWhy it Matters
Use with unsigned for clarityAvoids sign-related issues with shifts
Use masks with & and ``
Avoid unnecessary shifting large valuesCan lead to undefined behavior

Common Mistakes

MistakeProblem
Using signed int with shiftsMay cause unexpected results
Forgetting parenthesesBitwise has lower precedence than comparison
Misunderstanding ~aReturns 2’s complement, not just flipped bits