Course Content
C Tutorial
About Lesson

Bitwise Operations

Bitwise operations in C are fundamental techniques that manipulate individual bits within binary representations of data. These operations work directly at the binary level, allowing developers to perform tasks like setting, clearing, toggling, and checking specific bits within binary numbers.

Types of Bitwise Operators

C language provides several bitwise operators:

AND Operator (&)

The & operator performs a bitwise AND operation between two numbers. It sets a bit in the result only if the corresponding bits in both operands are set.

OR Operator (|)

The | operator performs a bitwise OR operation between two numbers. It sets a bit in the result if either of the corresponding bits in the operands is set.

XOR Operator (^)

The ^ operator performs a bitwise XOR (exclusive OR) operation between two numbers. It sets a bit in the result if the corresponding bits in the operands are different.

Complement Operator (~)

The ~ operator performs a bitwise NOT operation, which inverts all bits of a single operand.

Left Shift Operator (<<) and Right Shift Operator (>>)

The << and >> operators shift bits to the left or right, respectively. Shifting left (<<) multiplies the number by 2 for each shift, while shifting right (>>) divides the number by 2 for each shift.

Common Applications of Bitwise Operations

Manipulating Individual Bits

Bitwise operations are often used to manipulate individual bits efficiently. For instance, setting a particular bit in a number to 1 or 0, toggling bits, or checking if a specific bit is set.

Masking

Masking involves using bitwise operations to select or modify specific bits in a number while leaving others unchanged. It’s frequently used in programming for tasks such as data encryption, device control, or protocol handling.

Optimizations and Performance

In certain scenarios, bitwise operations can lead to more optimized code and improved performance, especially in low-level programming where direct manipulation of bits is crucial.

Example of Bitwise Operations in C

Consider a simple example where we toggle the third bit (from right to left) of a number x:

#include <stdio.h>

int main() {
int x = 10; // Binary: 1010

// Toggle the third bit
x = x ^ (1 << 2); // XOR with a mask to toggle the third bit

printf("Result after toggling: %dn", x); // Output: Result after toggling: 14 (Binary: 1110)
return 0;
}