Bitwise Rotate Right

后端 未结 5 2091
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-06 08:55

I am trying to convert this C function into Python;

typedef unsigned long var;
    /* Bit rotate rightwards */
    var ror(var v,unsigned int bits) {
        ret         


        
5条回答
  •  星月不相逢
    2021-02-06 09:12

    There are different problems in your question.

    C part :

    You use a value of key that is a 64 bits value (0x0f0f0f0f0f123456), but the output shows that for you compiler unsigned long is only 32 bits wide. So what C code does is rotating the 32 bits value 0x0f123456 16 times giving 0x34560f12

    If you had used unsigned long long (assuming it is 64 bits on your architecture as it is on mine), you would have got 0x34560f0f0f0f0f12 (rotation 16 times of a 64 bits)

    Python part :

    The definition of width between mask1 and ror is not consistent. mask1 takes a width in bits, where ror takes a width in bytes and one byte = 8 bits.

    The ror function should be :

    def ror(n, rotations=1, width=8):
        """Return a given number of bitwise right rotations of an integer n,
           for a given bit field width.
        """
        rotations %= width * 8  #  width bytes give 8*bytes bits
        if rotations < 1:
            return n
        mask = mask1(8 * width)  # store the mask
        n &= mask
        return (n >> rotations) | ((n << (8 * width - rotations)) & mask)  # apply the mask to result
    

    That way with key = 0x0f0f0f0f0f123456, you get :

    >>> hex(ror(key, 16))
    '0x34560f0f0f0f0f12L'
    >>> hex(ror(key, 16, 4))
    '0x34560f12L'
    

    exactly the same as C output

提交回复
热议问题