0
0
Cprogramming~5 mins

Bitwise AND, OR, XOR in C

Choose your learning style9 modes available
Introduction

Bitwise AND, OR, and XOR let you work directly with the bits inside numbers. This helps you do fast, low-level operations like turning bits on or off.

Checking if a specific bit in a number is on or off.
Setting or clearing a particular bit in a number.
Combining two numbers bit by bit to create a new number.
Performing simple encryption or toggling bits.
Optimizing performance in low-level programming or embedded systems.
Syntax
C
/* Bitwise operations on integers */
int bitwise_and = a & b;  // AND operation
int bitwise_or = a | b;   // OR operation
int bitwise_xor = a ^ b;  // XOR operation

The operators work on each bit of the numbers separately.

Operands must be integers (int, char, etc.).

Examples
Basic example showing bitwise AND, OR, XOR on two numbers.
C
int a = 6;  // binary 0110
int b = 3;  // binary 0011
int and_result = a & b;  // 2 (0010)
int or_result = a | b;   // 7 (0111)
int xor_result = a ^ b;  // 5 (0101)
Edge case: Using zero and one to see how bits combine.
C
int zero = 0;
int one = 1;
int and_zero = zero & one;  // 0
int or_zero = zero | one;   // 1
int xor_zero = zero ^ one;  // 1
Using all bits set to 1 to see how AND, OR, XOR behave.
C
int all_ones = ~0;  // all bits set to 1
int a = 5;  // 0101
int and_all_ones = a & all_ones;  // 5 (unchanged)
int or_all_ones = a | all_ones;    // -1 (all bits 1)
int xor_all_ones = a ^ all_ones;   // bitwise NOT of a
Sample Program

This program shows how bitwise AND, OR, and XOR work on two numbers. It prints the results so you can see the effect on bits.

C
#include <stdio.h>

int main() {
    int number1 = 12;  // binary 1100
    int number2 = 10;  // binary 1010

    printf("Number1: %d (binary 1100)\n", number1);
    printf("Number2: %d (binary 1010)\n", number2);

    int and_result = number1 & number2;
    int or_result = number1 | number2;
    int xor_result = number1 ^ number2;

    printf("Bitwise AND (number1 & number2): %d\n", and_result);
    printf("Bitwise OR (number1 | number2): %d\n", or_result);
    printf("Bitwise XOR (number1 ^ number2): %d\n", xor_result);

    return 0;
}
OutputSuccess
Important Notes

Time complexity is O(1) because bitwise operations happen directly on CPU registers.

Space complexity is O(1) as no extra memory is needed beyond variables.

Common mistake: Confusing bitwise operators (&, |, ^) with logical operators (&&, ||, !).

Use bitwise operations when you need to manipulate bits directly, not for general true/false logic.

Summary

Bitwise AND (&), OR (|), and XOR (^) work on each bit of integers.

They are useful for checking, setting, or toggling bits efficiently.

Remember: bitwise operators are different from logical operators.