I am trying to implement a rotate left function that rotates an integer x left by n bits
so far I have this:
int rotateLeft(int x, int n) {
return ((x << n) | (x >> (32 - n)));
}
which I have realized to not work for signed integers..does anyone have any ideas as how to fix this?
so now I tried:
int rotateLeft(int x, int n) {
return ((x << n) | ((x >> (32 + (~n + 1))) & 0x0f));
}
and receive the error:
ERROR: Test rotateLeft(-2147483648[0x80000000],1[0x1]) failed... ...Gives 15[0xf]. Should be 1[0x1]
int rotateLeft(int x, int n) {
return (x << n) | (x >> (32 - n)) & ~((-1 >> n) << n);
}
UPDATE:(thanks a lot @George)
int rotateLeft(int x, int n) {
return (x << n) | (x >> (32 - n)) & ~(-1 << n);
}
not use '-' version.
int rotateLeft(int x, int n) {
return (x << n) | (x >> (0x1F & (32 + ~n + 1))) & ~(0xFFFFFFFF << n);
}
//test program
int main(void){
printf("%x\n",rotateLeft(0x87654321,4));
printf("%x\n",rotateLeft(0x87654321,8));
printf("%x\n",rotateLeft(0x80000000,1));
printf("%x\n",rotateLeft(0x78123456,4));
printf("%x\n",rotateLeft(0xFFFFFFFF,4));
return 0;
}
/* result : GCC 4.4.3 and Microsoft(R) 32-bit C 16.00.40219.01
76543218
65432187
1
81234567
ffffffff
*/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With