如何让位旋转函数接受任何位大小?

发布于 2024-09-06 03:02:03 字数 772 浏览 1 评论 0原文

我有从其他代码中获得的这两个函数

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)

然而,当代码发生

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁人与我共长歌 2024-09-13 03:02:03

好吧,看看调用 ROL(x, n, 16) 时会发生什么。它调用 ROR(x,16-n),这相当于 ROR(x,16-n,32),但您真正想要的是 ROR (x,16-n,16)

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).

心不设防 2024-09-13 03:02:03

基本上,@GregS 的正确答案的含义是您需要在第二个实现中修复一个细节:(

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

我会将此作为注释,但随后我无法在其中提供可读格式的代码!-)。

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!-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文