移位

#include <iostream>
#include <cstdlib>
using namespace std;

unsigned int num;
unsigned int n;
void left()
{
for (int i = 0; i < n; ++i)
{
//if ((1 << 31) & num) (num <<= 1) |= 1;
//else num <<= 1;
if ((1 << 31) & num) (num = num << 1) |= 1;
else num = num << 1;
}
}

void right()
{
for (int i = 0; i < n; ++i)
{
//if (1 & num) (num >>= 1) |= (1 << 31);
//else num >>= 1;
if (1 & num) (num = num >> 1) |= (1 << 31);
else num = num >> 1;
}
}
void enter()
{
char buf[12];
cout << endl;
cout << "输入原始数字num:";
cin >> num;
cout << "输入要移的位n:";
cin >> n;
_itoa(num, buf, 2);
printf("原始数字 num = %s ", buf);
cout << endl;
}

int main()
{
char command = ' ';
char buf[12];
while (1)
{
cout << "输入指令<1 左移/ 2 右移/ 3 退出>:";
cin >> command;
if (command == '1')
{
enter();
left();
}
else if(command == '2')
{
enter();
right();
}
else if(command == '3')break;
_itoa(num, buf, 2);
printf("移位后 num = %s ", buf);
}
return 0;
}

原文地址:https://www.cnblogs.com/xpylovely/p/12660681.html