如何让位移函数接受任意位数?

1 投票
2 回答
7488 浏览
提问于 2025-04-16 00:05

我有这两个函数,是从其他代码里找到的。

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)

我想在一个需要进行16位旋转的程序中使用它们。不过,还有其他一些函数需要进行32位旋转,所以我想在公式中保留32位的部分,于是我得到了:

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)

但是,当我测试这组代码时,结果却不对。不过,当代码是

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)

时,结果就正确了。这是怎么回事,我该怎么解决这个问题呢?

2 个回答

3

简单来说,@GregS的正确回答的意思是,你需要在你的第二个实现中修正一个细节:

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

(我本来想把这做成评论的,但那样就不能把代码格式化得好看了!-)

6

好吧,看看当你调用 ROL(x, n, 16) 时发生了什么。它实际上会调用 ROR(x, 16-n),这和 ROR(x, 16-n, 32) 是一样的,但你真正想要的是 ROR(x, 16-n, 16)

撰写回答