Bitwise Operators in C

Bitwise operators perform operations on individual bits of integers. Here's a detailed explanation of each:

1. Bitwise AND (&)

int a = 5, b = 3;
printf("%d", a & b);  // Output: 1

Compares bits of a and b. Returns 1 only if both bits are 1.

a (5)b (3)a & b
010100110001 (1)

2. Bitwise OR (|)

int a = 5, b = 3;
printf("%d", a | b);  // Output: 7

Compares bits of a and b. Returns 1 if either bit is 1.

a (5)b (3)a | b
010100110111 (7)

3. Bitwise XOR (^)

int a = 5, b = 3;
printf("%d", a ^ b);  // Output: 6

Compares bits of a and b. Returns 1 if bits are different.

a (5)b (3)a ^ b
010100110110 (6)

4. Bitwise NOT (~)

int a = 5;
printf("%d", ~a);  // Output: -6

Inverts all bits of the number.

In 32-bit systems: ~00000000 00000000 00000000 00000101 = 11111111 11111111 11111111 11111010

This represents -6 in 2’s complement form.

5. Left Shift (<<)

int a = 5;
printf("%d", a << 1);  // Output: 10

Shifts all bits to the left by the specified number of positions.

0101 << 1 becomes 1010 → 10

Each left shift is equivalent to multiplying by 2.

6. Right Shift (>>)

int a = 5;
printf("%d", a >> 1);  // Output: 2

Shifts all bits to the right by the specified number of positions.

0101 >> 1 becomes 0010 → 2

Each right shift is equivalent to dividing by 2 (ignoring remainder).