Implement a cyclic right shift for K discharges.
Example: K = 2
00011010 10 => 10 00011010.
if not difficult, then with more or less clear explanations, I will be very grateful
Implement a cyclic right shift for K discharges.
Example: K = 2
00011010 10 => 10 00011010.
if not difficult, then with more or less clear explanations, I will be very grateful
Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .
Read the code and understand:
#include <iostream> #include <bitset> using namespace std; const unsigned int BYTE = 10; // количество разрядов const unsigned int STEP = 2; // на сколько шагов нужно будет сдвинуть int main(){ bitset<BYTE> bit(106), part1, part2, result; cout << "bit\t" << bit << endl; // исходное число // результат будет составлен из двух частей part1 = bit >> STEP; // первая часть, два сдвига вправо cout << "part1\t" << part1 << endl; part2 = bit << BYTE - STEP; // вторая часть, восемь сдвигов влево (десять разрядов числа минус два шага) cout << "part2\t" << part2 << endl; result = part1 | part2; // объеденияем части cout << "result\t" << result << endl; // результат объединения частей return 0; }
conclusion:
like that
unsigned int x = 0x1234ABCD; int k = 2; x = (x >> k) | (x << (32 - k));
instead of 32, substitute the required value if different
int
to the right is unsafe and depends on the implementation. For this formula to work, x >> k
must necessarily use a logical shift, and this is not guaranteed. - ixSciunsigned
- Yuriy Orlovstd::vector<bool>
+ std::rotate
= execution result
#include <iostream> #include <algorithm> #include <vector> using BinVec = std::vector<bool>; void print(const BinVec& v) { for(bool b : v) std::cout << b; std::cout << "\n"; } void shr(BinVec& 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 to work with bits. The code created with its help is probably not the most optimal, but very visual. Shift implementation example :
#include <iostream> #include <bitset> int main() { std::bitset<10> baz ("0001101010"); // 10-количество бит в числе for(int i=0; i<2; i++) // 2-на сколько бит сдвигаем { bool temp = baz[0]; baz >>= 1; // >> - сдвиг вправо baz[baz.size()-1] = temp; } std::cout << baz; }
Source: https://ru.stackoverflow.com/questions/501146/
All Articles