56 lines
1.2 KiB
C++
56 lines
1.2 KiB
C++
#include <iostream>
|
|
#include <iomanip>
|
|
|
|
using namespace std;
|
|
|
|
unsigned int rotateLeft(unsigned int x, int n);
|
|
unsigned int rotateRight(unsigned int x, int n);
|
|
void stampaBinario(unsigned int x);
|
|
|
|
int main(void) {
|
|
unsigned int x = 5;
|
|
int n = 1;
|
|
|
|
cout << "Numero originale: " << setw(19) << x << setw(5) << " => ";
|
|
stampaBinario(x);
|
|
|
|
unsigned int left = rotateLeft(x, n);
|
|
unsigned int right = rotateRight(x, n);
|
|
|
|
cout << "Rotazione a sinistra di " << n << ": " << setw(10) << left << setw(2) << " => ";
|
|
stampaBinario(left);
|
|
|
|
cout << "Rotazione a destra di " << n << ": " << setw(12) << right << " => ";
|
|
stampaBinario(right);
|
|
cout << endl;
|
|
|
|
return 0;
|
|
}
|
|
|
|
unsigned int rotateLeft(unsigned int x, int n) {
|
|
const int bitSize = 32;
|
|
|
|
n = n % bitSize;
|
|
|
|
return ((x << n) | (x >> (bitSize - n))) & 0xFFFFFFFF;
|
|
}
|
|
|
|
unsigned int rotateRight(unsigned int x, int n) {
|
|
const int bitSize = 32;
|
|
|
|
n = n % bitSize;
|
|
|
|
return ((x >> n) | (x << (bitSize - n))) & 0xFFFFFFFF;
|
|
}
|
|
|
|
void stampaBinario(unsigned int x) {
|
|
for (int i = 31; i >= 0; i--) {
|
|
cout << ((x >> i) & 1);
|
|
|
|
if (i % 8 == 0) {
|
|
cout << ' ';
|
|
}
|
|
}
|
|
|
|
cout << endl;
|
|
} |