Home c++ Cyclic shift right by K bits

# Cyclic shift right by K bits

Author

Date

Category

Implement a circular shift to the right by K bits.

Example: K = 2

00011010 10 = & gt; 10 00011010.

if not difficult, then with more or less clear explanations, I will be very grateful

something like this

``````unsigned int x = 0x1234ABCD;
int k = 2;
x = (x & gt; & gt; k) | (x & lt; & lt; (32 - k));
``````

replace 32 with the required value, if different

``````# include & lt; iostream & gt;
#include & lt; bitset & gt;
using namespace std;
const unsigned int BYTE = 10; // number of digits
const unsigned int STEP = 2; // how many steps will need to be shifted
int main () {
bitset & lt; BYTE & gt; bit (106), part1, part2, result;
cout & lt; & lt; "bit \ t" & lt; & lt; bit & lt; & lt; endl; // original number
// the result will be composed of two parts
part1 = bit & gt; & gt; STEP; // first part, two right shifts
cout & lt; & lt; "part1 \ t" & lt; & lt; part1 & lt; & lt; endl;
part2 = bit & lt; & lt; BYTE - STEP; // second part, eight shifts to the left (ten digits of the number minus two steps)
cout & lt; & lt; "part2 \ t" & lt; & lt; part2 & lt; & lt; endl;
result = part1 | part2; // merge parts
cout & lt; & lt; "result \ t" & lt; & lt; result & lt; & lt; endl; // result of combining parts
return 0;
}
``````

output:

``````# include & lt; iostream & gt;
#include & lt; algorithm & gt;
#include & lt; vector & gt;
using BinVec = std :: vector & lt; bool & gt ;;
void print (const BinVec & amp; v)
{
for (bool b: v)
std :: cout & lt; & lt; b;
std :: cout & lt; & lt; "\ n";
}
void shr (BinVec & amp; v, int k)
{
k% = v.size ();
std :: rotate (v.begin (), v.end () - k, v.end ());
}
int main ()
{
BinVec v (8);
v [0] = 1;
print (v);
shr (v, 2);
print (v);
}
``````

C++ has a standard library for working with bits. The code created with its help is probably not the most optimal, but very descriptive. Example implementation with offset:

``````# include & lt; iostream & gt;
#include & lt; bitset & gt;
int main ()
{
std :: bitset & lt; 10 & gt; baz ("0001101010"); // 10-number of bits in the number
for (int i = 0; i & lt; 2; i ++) // 2-how many bits we shift
{
bool temp = baz [0];
baz & gt; & gt; = 1; // & gt; & gt; - shift to the right
baz [baz.size () - 1] = temp;
}
std :: cout & lt; & lt; baz;
}
``````

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.