Home

Bitwise Operations in C: AND, OR, and XOR Explained

Bitwise operations work directly on the binary representation of numbers. They’re fundamental to low-level programming, enabling efficient manipulation of individual bits. Let’s explore the three most common bitwise operators: AND (&), OR (|), and XOR (^).

Bitwise AND (&)

The AND operator compares each bit of two numbers and returns 1 only if both bits are 1. Otherwise, it returns 0.

  5 = 0101 (binary)
  3 = 0011 (binary)
--------
  1 = 0001 (result)

Truth table for AND:

A | B | A & B
---|---|------
0 | 0 |   0
0 | 1 |   0
1 | 0 |   0
1 | 1 |   1

Common uses:

Bitwise OR (|)

The OR operator compares each bit and returns 1 if at least one of the bits is 1.

  5 = 0101 (binary)
  3 = 0011 (binary)
--------
  7 = 0111 (result)

Truth table for OR:

A | B | A | B
---|---|-----
0 | 0 |   0
0 | 1 |   1
1 | 0 |   1
1 | 1 |   1

Common uses:

Bitwise XOR (^)

The XOR (exclusive OR) operator returns 1 if the bits are different, and 0 if they’re the same.

  5 = 0101 (binary)
  3 = 0011 (binary)
--------
  6 = 0110 (result)

Truth table for XOR:

A | B | A ^ B
---|---|------
0 | 0 |   0
0 | 1 |   1
1 | 0 |   1
1 | 1 |   0

Common uses:

Complete C Example

Here’s a program that demonstrates all three operations:

#include <stdio.h>

int main(void)
{
    printf("5 in binary is: %04b\n", 5);
    printf("3 in binary is: %04b\n", 3);
    printf("Binary of '5 & 3' is: %04b\n", 5 & 3); // AND
    printf("Decimal of '5 & 3' is: %d\n", 5 & 3); // AND
    printf("Binary of '5 | 3' is: %04b\n", 5 | 3); // OR
    printf("Decimal of '5 | 3' is: %d\n", 5 | 3); // OR
    printf("Binary of '5 ^ 3' is: %04b\n", 5 ^ 3); // XOR
    printf("Decimal of '5 ^ 3' is %d\n", 5 ^ 3); // XOR

    return 0;
}

Output:

5 in binary is: 0101
3 in binary is: 0011
Binary of '5 & 3' is: 0001
Decimal of '5 & 3' is: 1
Binary of '5 | 3' is: 0111
Decimal of '5 | 3' is: 7
Binary of '5 ^ 3' is: 0110
Decimal of '5 ^ 3' is 6

Notice!

The %04b format specifier is a GCC extension that prints integers in binary format with zero-padding to 4 digits. This is particularly useful for visualizing bitwise operations. Standard C doesn’t include a binary format specifier, which is why this extension comes in handy for learning and debugging bitwise code.

Tags: CAlgorithmsLinux