C program to rotate the bits for a given number

Bit rotation is a fundamental bitwise operation where bits in a number are shifted circularly. In left rotation, bits move left and the leftmost bit wraps to the rightmost position. In right rotation, bits move right and the rightmost bit wraps to the leftmost position.

Syntax

// Left rotation
int leftRotate(int num, int rotations);

// Right rotation  
int rightRotate(int num, int rotations);

Key Concepts

  • Left rotation: Bits are shifted left, MSB wraps to LSB position
  • Right rotation: Bits are shifted right, LSB wraps to MSB position
  • Circular shift: No bits are lost during rotation
  • Rotation count should be optimized using modulo operation

Example 1: Left Rotation

This program demonstrates left rotation where bits are shifted towards the left −

#include <stdio.h>

int leftRotate(int num, int rotations) {
    int size = sizeof(int) * 8;
    rotations = rotations % size;
    
    return (num << rotations) | (num >> (size - rotations));
}

int main() {
    int number = 12;
    int rotate = 2;
    
    printf("Original number: %d<br>", number);
    printf("Left rotation by %d positions: %d<br>", rotate, leftRotate(number, rotate));
    
    return 0;
}
Original number: 12
Left rotation by 2 positions: 48

Example 2: Right Rotation

This program demonstrates right rotation where bits are shifted towards the right −

#include <stdio.h>

int rightRotate(int num, int rotations) {
    int size = sizeof(int) * 8;
    rotations = rotations % size;
    
    return (num >> rotations) | (num << (size - rotations));
}

int main() {
    int number = 18;
    int rotate = 2;
    
    printf("Original number: %d<br>", number);
    printf("Right rotation by %d positions: %d<br>", rotate, rightRotate(number, rotate));
    
    return 0;
}
Original number: 18
Right rotation by 2 positions: 4

How It Works

Left Rotation (12 Original: 0000 1100 Rotated: 0011 0000 (48) Bits move left Right Rotation (18 >> 2): Original: 0001 0010 Rotated: 0000 0100 (4) Bits move right

Conclusion

Bit rotation is efficiently implemented using bitwise shift operators combined with OR operations. The modulo operation ensures rotation count stays within valid range, and the technique preserves all bits in a circular manner.

Updated on: 2026-03-15T13:27:46+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements