Back to course

Bitwise Operators

C Language: 0 to Hero - The Complete Beginner's Guide

Lesson 56: Bitwise Operators

Bitwise operators work on the individual bits (0s and 1s) of integer types. They are essential for low-level programming, encryption, network programming, and optimizing storage.

OperatorDescription
&Bitwise AND (Sets a bit if both corresponding bits are 1)
``
^Bitwise XOR (Sets a bit if the corresponding bits are different)
~Bitwise NOT (Flips all bits: 0 becomes 1, 1 becomes 0)
<<Left Shift (Shifts bits left, filling right with 0s)
>>Right Shift (Shifts bits right)

Practical Use: Setting, Clearing, and Toggling Bits

Assume we have an 8-bit integer flags.

1. Setting a Bit (Using OR |)

To ensure the 3rd bit (index 2) is 1, regardless of its current state:

c unsigned char flags = 0b00100000; // Example value 32 unsigned char MASK = 0b00000100; // Mask for bit 2 (value 4)

// Set bit 2 (32 | 4 = 36) flags = flags | MASK;

2. Clearing a Bit (Using AND & with NOT ~)

To ensure the 5th bit (index 4) is 0:

c unsigned char flags = 0b00110000; // Example value 48 unsigned char MASK = 0b00010000; // Mask for bit 4 (value 16)

// Clear bit 4 (48 & ~16 = 32) flags = flags & (~MASK);

3. Bit Shifting

Left shift (<<) is equivalent to multiplying by powers of 2 (if overflow doesn't occur).

c int x = 5; // 00000101 int y = x << 2; // 00010100 (20). 5 * 2^2 = 20.