I am trying to convert this C function into Python;
typedef unsigned long var;
/* Bit rotate rightwards */
var ror(var v,unsigned int bits) {
return (v>>bits)|(v<<(8*sizeof(var)-bits));
}
I have tried Googling for some solutions, but I can't seem to get any of them to give the same results as the one here.
This is one solution I have found from another program;
def mask1(n):
"""Return a bitmask of length n (suitable for masking against an
int to coerce the size to a given length)
"""
if n >= 0:
return 2**n - 1
else:
return 0
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
if rotations < 1:
return n
n &= mask1(width)
return (n >> rotations) | ((n << (8 * width - rotations)))
I am trying to btishift key = 0xf0f0f0f0f123456
. The C code gives 000000000f0f0f12
when it is called with; ror(key, 8 << 1)
and Python gives; 0x0f0f0f0f0f123456
(the original input!)
Your C output doesn't match the function that you provided. That is presumably because you are not printing it correctly. This program:
produces the following output:
To produce an ror function in Python I refer you to this excellent article: http://www.falatic.com/index.php/108/python-and-bitwise-rotation
This Python 2 code produces the same output as the C program above:
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 value0x0f123456
16 times giving0x34560f12
If you had used
unsigned long long
(assuming it is 64 bits on your architecture as it is on mine), you would have got0x34560f0f0f0f0f12
(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 :That way with
key = 0x0f0f0f0f0f123456
, you get :exactly the same as C output