How to get bit rotation function to accept any bit size?

Posted by calccrypto on Stack Overflow See other posts from Stack Overflow or by calccrypto
Published on 2010-06-16T22:49:25Z Indexed on 2010/06/16 22:52 UTC
Read the original article Hit count: 289

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about math