/*
C program
Task:
* rotateLeft - Rotate x to the left by n bits
* Can assume that 0 <= n <= 31
* Examples: rotateLeft(0x87654321,4) = 0x76543218
* Legal ops: ~ & ^ | + << >> !
* Max ops: 25
* Rating: 3
*/
int rotateLeft(int x, int n) {
int mask=0xFFFFFFFF;
int out;
// initialize out with value x
out = x;
printf("Number in hexadecimal is %0x\n",x);
printf("Initialize mask = %X\n",mask);
printf("Show rotateLeft(0x87654321,4) = 0x76543218\n");
out = out >> (32-n);
printf("Right shift the number by (32 - %d)=%d bit. out= %X\n",n,
(32-n), out);
mask = mask << n;
printf("left shift mask by %d bit mask = %X\n", n, mask);
mask=~mask;
printf("New mask after Inverse mask = %X\n",mask);
out = out & mask;
printf("Bitwise ANDing of out = out & mask. Changed out =
%X\n", out);
//left shift the original number
x = x<<n;
printf("left shift the original Number by %d , so x = %X\n", n,
x);
out = x + out;
printf("Bitwise OR of x + out = %X\n", out);
return out;
}
int main()
{
printf("%0x",rotateLeft(0x87654321,4));
return 0;
}
Output:
Number in hexadecimal is 87654321
Initialize mask = FFFFFFFF
Show rotateLeft(0x87654321,4) = 0x76543218
Right shift the number by (32 - 4)=28 bit. out= FFFFFFF8
left shift mask by 4 bit mask = FFFFFFF0
New mask after Inverse mask = F
Bitwise ANDing of out = out & mask. Changed out = 8
left shift the original Number by 4 , so x= 76543210
Bitwise OR of x + out = 76543218
76543218
Get Answers For Free
Most questions answered within 1 hours.