Bitwise rotate left function

后端 未结 6 1491
一向
一向 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 10:55

    The best way is:

    int rotateLeft(int x, int n)
    {
        _asm
        {
            mov eax, dword ptr [x]
            mov ecx, dword ptr [n]
            rol eax, cl
        }
    }
    

    If you need to rotate an int variable right in your code, then the fastest way is:

    #define rotl( val, shift ) _asm mov eax, dword ptr[val] _asm mov ecx, dword ptr [shift] _asm rol eax, cl _asm mov dword ptr [val], eax
    

    val is the value you rotate, shift is the length of the rotation.

提交回复
热议问题