<
HTML EDITOR C JAVA PHP

C Bitwise Operators: Manipulating Bits

Bitwise Operators are used to perform operations at the bit level (0s and 1s). While most operations work with bytes or words, bitwise operators allow you to modify individual bits within a variable. This is extremely useful in low-level programming, device drivers, and data compression.

1. The Core Bitwise Operators

C provides six bitwise operators. These work only on integer-type data (int, char, short, etc.) and cannot be used with float or double.

Operator Meaning Description
& Binary AND Sets bit to 1 if both bits are 1.
| Binary OR Sets bit to 1 if at least one bit is 1.
^ Binary XOR Sets bit to 1 if bits are different.
~ Binary NOT Inverts all bits (0 to 1, 1 to 0).

2. Bitwise Shift Operators

Shift operators move the bits of a variable to the left or right, which is a very fast way to perform multiplication or division by powers of two.

int a = 5; // Binary: 00000101
int b = a << 1; // Binary: 00001010 (Value: 10)
int c = a >> 1; // Binary: 00000010 (Value: 2)

3. Bit Masking

Masking is a technique used to check, set, or clear specific bits in a number without affecting the other bits.

// Checking if the 3rd bit is set
if (num & (1 << 2)) {
    printf("3rd bit is ON");
}

// Setting the 3rd bit to ON
num = num | (1 << 2);

// Clearing (turning OFF) the 3rd bit
num = num & ~(1 << 2);

4. Practical Use Case: Even or Odd?

Using the bitwise AND operator is much faster than using the modulo (%) operator to check if a number is even or odd.

int n = 7;
if (n & 1) {
    printf("Odd");
} else {
    printf("Even");
}

5. Technical Specifications

Efficiency Executed directly by the CPU ALU in a single clock cycle.
Endianness Bitwise operations are independent of Big/Little Endian byte order.
Pro Tip: You can swap two numbers without using a temporary variable by using the XOR operator: a^=b; b^=a; a^=b;. It's a classic interview trick!