This Program is to perform Right and Left rotate Operation
What is rotation of a number by a bit?
Rotation of a number by a particular bit can be:
- Left Rotation
- Right Rotation
Left Rotation:
This means shifting all the bits to the left and pushing the dropped Most significant bit(MSB) to the Least significant bit(LSB).
Right Rotation:
This means shifting all the bits to the right and pushing the dropped Least significant bit(LSB) to the Most significant bit(MSB).

Logic:
Example:
Number =16
shift bit = 2
16 = 0 0 0 1 0 0 0 0
1) perform Left shift by 2
= 0 0 0 0 0 0 0 0
After doing this we loose the Total bits – shift bits from the MSB which has to made as LSB
2) But in rotation total_bits – shift_bit has to go as LSB
To do this
Perform Right shift of the given number by total_bits – shift_bits
Once after doing this, 2 bits from MSB became as LSB and rest 0
After doing that result is 0 1 0 0 0 0 0 0
3) Now we perform OR operation between 1 and 2
So answer is 64
Left shift means by multiplying that number by power of 2 by that bit
Right Shift:
Example:
Number =16
pos =2
16 = 0 0 0 1 0 0 0 0
1) perform Right shift by 2
= 0 0 0 0 0 1 0 0
2) Now in Right Rotate,last(LSB) 2(pos No of bits) has to become MSB. For that
Shift the number to left by (Total_bits – pos) bits.
Number : 0 0 0 1 0 0 0 0
Total_bits -pos = 0 0 0 0 0 0 0 0
3) Now we need to OR 1 and 2
0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0
————————-
0 0 0 0 0 1 0 0
So answer is 4
Right shift means dividing the Number by power of 2 to that bit
#include <stdio.h>
#define MAX_BIT (sizeof(int) * 8)
#define left_rotation(num, bit) ((num << bit) | num >> (MAX_BIT- bit))
#define right_rotation(num, bit) (( num >>bit) | num << (MAX_BIT -bit))
int display_binary(unsigned int num)
{
int i;
for(i = MAX_BIT-1; i>=0; i--)
{
if((num >> i)&1)
printf("1");
else
printf("0");
}
}
int main()
{
unsigned int num,left_bit, right_bit;
printf("\n Enter the Number : ");
scanf("%d", &num);
printf("\n Enter the left rotation bit : ");
scanf("%d", &left_bit);
printf("\n Enter the right rotation bit : ");
scanf("%d", &right_bit);
printf("\n The number in binary is:");
display_binary(num);
printf("\n The number after left rotation is: %u\n", left_rotation(num, left_bit));
printf("\n The number after right rotation is: %u\n", right_rotation(num, right_bit));
return 0;
}
Output:
Enter the Number : 12
Enter the left rotation bit : 2
Enter the right rotation bit : 2
The number in binary is:00000000000000000000000000001100
The number after rotation is: 48
The number after rotation is: 3
Categories: C Language
Leave a Reply