Bitwise Operators in C

Bitwise operators in C are used to perform operations at the bit level. They work with integers and perform operations on their binary representations. These operators are essential for low-level programming, such as device drivers or embedded systems, where direct manipulation of bits is required.

Types of Bitwise Operators

There are six main bitwise operators in C:

Bitwise Operators Syntax

The syntax for using bitwise operators is as follows:

syntax

            
result = operand1 <operator> operand2;

        

Here, the operator can be any of the bitwise operators listed above, and the operands are integer values.

Examples of Bitwise Operators

Bitwise AND (&)

The bitwise AND operator compares each bit of two integers and returns 1 if both corresponding bits are 1; otherwise, it returns 0.

Example

        
#include <stdio.h>
int main() 
{
    int a = 5, b = 3;
    int result = a & b;  // Bitwise AND

    printf("Result of %d & %d = %d\n", a, b, result);
    return 0;
}
        
    

Output

Result of 5 & 3 = 1

Bitwise OR (|)

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

Example

        
#include <stdio.h>
int main() 
{
    int a = 5, b = 3;
    int result = a | b;  // Bitwise OR

    printf("Result of %d | %d = %d\n", a, b, result);
    return 0;
}
        
    

Output

Result of 5 | 3 = 7

Bitwise XOR (^)

The bitwise XOR operator compares each bit of two integers and returns 1 if the corresponding bits are different.

Example

        
#include <stdio.h>
int main() 
{
    int a = 5, b = 3;
    int result = a ^ b;  // Bitwise XOR

    printf("Result of %d ^ %d = %d\n", a, b, result);
    return 0;
}
        
    

Output

Result of 5 ^ 3 = 6

Bitwise NOT (~)

The bitwise NOT operator inverts each bit of the operand. 1 becomes 0, and 0 becomes 1.

Example

        
#include <stdio.h>
int main() 
{
    int a = 5;
    int result = ~a;  // Bitwise NOT

    printf("Result of ~%d = %d\n", a, result);
    return 0;
}
        
    

Output

Result of ~5 = -6

Bitwise Left Shift (<<)

The left shift operator shifts the bits of the operand to the left by the specified number of positions, filling with zeros on the right.

Example

        
#include <stdio.h>
int main() 
{
    int a = 5;
    int result = a << 1;  // Left shift by 1

    printf("Result of %d << 1 = %d\n", a, result);
    return 0;
}
        
    

Output

Result of 5 << 1 = 10

Bitwise Right Shift (>>)

The right shift operator shifts the bits of the operand to the right by the specified number of positions. The behavior for signed integers can vary based on the system.

Example

        
#include <stdio.h>
int main() 
{
    int a = 5;
    int result = a >> 1;  // Right shift by 1

    printf("Result of %d >> 1 = %d\n", a, result);
    return 0;
}
        
    

Output

Result of 5 >> 1 = 2

Advantages of Bitwise Operators

Disadvantages of Bitwise Operators