views:

48

answers:

2

i have these 2 functions i got from some other code

def ROR(x, n):
    mask = (2L**n) - 1
    mask_bits = x & mask
    return (x >> n) | (mask_bits << (32 - n))

def ROL(x, n):
    return ROR(x, 32 - n)

and i wanted to use them in a program, where 16 bit rotations are required. however, there are also other functions that require 32 bit rotations, so i wanted to leave the 32 in the equation, so i got:

def ROR(x, n, bits = 32):
    mask = (2L**n) - 1
    mask_bits = x & mask
    return (x >> n) | (mask_bits << (bits - n))

def ROL(x, n, bits = 32):
    return ROR(x, bits - n)

however, the answers came out wrong when i tested this set out. yet, the values came out correctly when the code is

def ROR(x, n):
    mask = (2L**n) - 1
    mask_bits = x & mask
    return (x >> n) | (mask_bits << (16 - n))

def ROL(x, n,bits):
    return ROR(x, 16 - n)

what is going on and how do i fix this?

+3  A: 

Well, just look at what happens when you call ROL(x, n, 16). It calls ROR(x,16-n), which is equivalent to ROR(x,16-n,32), but what you really wanted was ROR(x, 16-n, 16).

GregS
First ROR should be ROL?
PreludeAndFugue
yes, thanks. EDITED.
GregS
A: 

Basically, the implication of @GregS's correct answers are that you need to fix one detail in your second implementation:

def ROL(x, n, bits=32):
    return ROR(x, bits - n, bits)

(I'd make this a comment, but then I couldn't have readably formatted code in it!-).

Alex Martelli