write a C++ program for logical cyclic shift of n-bit numbers by given number of
ID: 3665723 • Letter: W
Question
write a C++ program for logical cyclic shift of n-bit numbers by
given number of positions (<= n).
You are required to create a circular list to store a given binary number. Then your
program will be able to rotate the number left by any given number of positions for the
cyclic left operation, and rotate the number by right by a given number of positions for
the cyclic right operation. The provided sample input below elaborates on these
In this assignment you are required to use a circular array to create a circular
representation for the n-bit number. The cyclic shift operations will change where the
first bit starts in the number. The cyclic shift left by one position shifts every bit to the
left by one position; and the leftmost bit moves cyclically to the vacated rightmost
position. Similarly, the cyclic shift right shifts every bit to the right by one position; and
the rightmost bit is moved cyclically to the vacated leftmost position. These generalize to
cyclic shifts (left and right) by any given number of positions in an obvious way.
/* next inputs are n bits, from leftmost bit to rightmost bit =*/ 1 1 1 1 0 0 0 0
L 1 /* rotate left by one position */
L 2 /* rotate left by two positions*/
The above is one simple example your program must be designed to work for every n and
every n-bit number, and for every number of positions (<= n).
Explanation / Answer
#include<stdio.h>
#define INT_BITS 32
/*Function to left rotate n by d bits*/
int leftRotate(int n, unsigned int d)
{
/* In n<<d, last d bits are 0. To put first 3 bits of n at
last, do bitwise or of n<<d with n >>(INT_BITS - d) */
return (n << d)|(n >> (INT_BITS - d));
}
/*Function to right rotate n by d bits*/
int rightRotate(int n, unsigned int d)
{
/* In n>>d, first d bits are 0. To put last 3 bits of at
first, do bitwise or of n>>d with n <<(INT_BITS - d) */
return (n >> d)|(n << (INT_BITS - d));
}
/* Driver program to test above functions */
int main()
{
int n = 16;
int d = 2;
printf("Left Rotation of %d by %d is ", n, d);
printf("%d", leftRotate(n, d));
printf(" Right Rotation of %d by %d is ", n, d);
printf("%d", rightRotate(n, d));
getchar();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.