There are different problems in your question.
Part C:
You are using a key value whose value is 64 bits ( 0x0f0f0f0f0f123456 ), but the output shows that for your compiler unsigned long is only 32 bits. So what the C code does, rotates the 32-bit value 0x0f123456 16 times, giving 0x34560f12
If you used unsigned long long (assuming it is 64 bits in your architecture, like mine), you would get 0x34560f0f0f0f0f12 (rotation 16 times out of 64 bits)
Python part:
The definition of the width between mask1 and ror is not compatible. mask1 takes the width in bits, where ror takes the 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
So using key = 0x0f0f0f0f0f123456 you get:
>>> hex(ror(key, 16)) '0x34560f0f0f0f0f12L' >>> hex(ror(key, 16, 4)) '0x34560f12L'
exactly the same as pin C
Serge Ballesta
source share