I am trying to implement a rotate left function that rotates an integer x left by n bits
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
*/