Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
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.
Advertisements
