
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rotate Bits for a Given Number in C
Consider the factors given below to write a C program to rotate the bits for a given number.
Rotating the bit from left to right or right to left.
In left rotation, the bits are shifted from left to right.
In right rotation, the bits are shifted from right to left.
Take a number and try to rotate either left or right based on user program.
User has to enter the number rotation at run time along with a number.
Program 1
Following is the C program to apply left rotation for a given number.
#include<stdio.h> #include<stdlib.h> int main(){ int number, rotate, Msb, size; printf("Enter any number:"); scanf("%d",&number); printf("Enter number of rotations:
"); scanf("%d",&rotate); size = sizeof(int) * 8; rotate %= size; while(rotate--){ Msb = (number >> size) & 1; number = (number << 1) | Msb; } printf("After Left rotation the value is = %d
",number); return 0; }
Output
When the above program is executed, it produces the following result −
Enter any number:12 Enter number of rotations: 2 After Left rotation the value is = 48
Program 2
Given below is the C program to apply right rotation for a given number.
#include<stdio.h> #include<stdlib.h> int main(){ int number,rotate, Lsb, size; printf("Enter any number:"); scanf("%d",&number); printf("Enter number of rotations:
"); scanf("%d",&rotate); size = sizeof(int) * 8; rotate %= size; while(rotate--){ Lsb = number & 1; number = (number >> 1) &(~(1<<size)); number=number|(Lsb<<size); } printf("After right rotation the value is = %d
",number); return 0; }
Output
When the above program is executed, it produces the following result −
Enter any number:18 Enter number of rotations: 2 After right rotation the value is = 4
Advertisements