The goal is to write a method that moves n number of bits in a 32 bit machine to the left by only using ~, !, |, &, ^, +, >>, << (no for loops, if statements, so on...). I think that what I've got should work. My problem is that the variable move_left seems to not behave properly. Here is my code which is broken down into steps in order for me to track down the problem:
int rotateLeft(int x, int n)
{
int move_left = (0x20 + (~n + 1)); // 32 - n
int expr1 = x >> n; // chopping off n bits on the right
int expr2 = ~((~0x0) << n); // n number of 1s on the right
int expr3 = expr2 & x; // the bits that now need to be on the left
int expr4 = expr3 << move_left; // the correct bits on the left
int expr7 = ~0x0 << move_left; // breaking down expr5
int expr5 = (~((~0x0) << move_left)); //
int expr6 = expr5 & expr1; // copying the right sided body
int result = expr6 | expr4; //adding the left side
printf("%d\n%d\n%d\n%d\n%d\n%d\n", move_left, expr1, expr7, expr5, expr6, expr4);
return result;
}
When testing with rotateLeft(-2147483648[0x80000000],0[0x0]) the result, however, is incorrect. When tracking down my arguments, the print is:
32
-2147483648
-1
0
0
0
I do not understand how move_left is 32 (which is right), but ~0x0 << move_left is somehow -1 when it should be 0! (When I substitute left_right with 0x20 in expr7, then it prints 0 correctly.)
I appreciate any help!