Bitwise rotate left function

后端 未结 6 1490
一向
一向 2020-11-30 10:18

I am trying to implement a rotate left function that rotates an integer x left by n bits

  • Ex: rotateLeft(0x87654321,4) = 0x76543218
  • Legal ops: ~ &
6条回答
  •  旧巷少年郎
    2020-11-30 11:04

    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
    */
    

提交回复
热议问题