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
There are different problems in your question.
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)
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