write a C++ program for logical cyclic shift of n-bit numbers by given number of
ID: 3667484 • 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 operations.
In this assignment you are required to use a circular linked list 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.
You may choose to use doubly-linked circular linked list, or make a full circular traversal on each cyclic shift as we discussed in the lecture.
/* first input n = */ 8
/* 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 */
result=11100001
L 2 /* rotate left by two positions*/
result=10000111
L 1 /* rotate left */
result=00001111
R 3 /* rotate right */
result=11100001
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
Below is given a c++ program for rotation in left as well as right
#include<iostream>
#include<bitset>
#define BINARY_BITS 8
using namespace std;
int rotateToLeft(int val, unsigned int pos)
{
return (val << pos)|(val >> (BINARY_BITS - pos));
}
int rotateToRight(int val, unsigned int pos)
{
return (val >> pos)|(val << (BINARY_BITS - pos));
}
int main()
{
long binarynum,remender, num, baseVal = 1;
int n, rotate;
cout << "Please enter binary number of 8 bits: ";
cin >> num;
binarynum = num;
while (num > 0)
{
remender = num % 10;
n = n + remender * baseVal;
baseVal = baseVal * 2;
num = num / 10;
}
cout <<"How many position you want to do left shift"<<endl;
cin>>rotate;
int n1 = rotateToLeft(n, rotate);
cout<<"Value after left rotation: ";
std::bitset<8> binarynum_x(n1);
std::cout << binarynum_x<<endl;
cout <<"How many position you want to do right shift"<<endl;
cin>>rotate;
int n2 = rotateToRight(n, rotate);
cout<<"Value after right rotation: ";
std::bitset<8> binarynum_x1(n2);
std::cout << binarynum_x1<<endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.