大多數計算機處理器提供了機器級的循環命令,但在C和C++中,不直接支持循環,因此需要創建自己的循環命令。下面是實現左旋和右旋的函數:
#include <iostream>
#include <bitset>
using namespace std;
void rol(unsigned char& val) {
int highbit;
if (val & 0x80)
highbit = 1;
else
highbit = 0;
val <<= 1;
val |= highbit;
}
void ror(unsigned char& val) {
int lowbit;
if (val & 0x01)
lowbit = 1;
else
lowbit = 0;
val >>= 1;
val |= lowbit;
}
int main()
{
unsigned char x = 127;
cout << bitset<sizeof(unsigned char) * 8>(x) << endl;
rol(x);
cout << bitset<sizeof(unsigned char) * 8>(x) << endl;
ror(x);
cout << bitset<sizeof(unsigned char) * 8>(x) << endl;
system("pause");
return 0;
}