如何让位旋转函数接受任何位大小?
我有从其他代码中获得的这两个函数
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,看看调用
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 callsROR(x,16-n)
, which is equivalent toROR(x,16-n,32)
, but what you really wanted wasROR(x, 16-n, 16)
.基本上,@GregS 的正确答案的含义是您需要在第二个实现中修复一个细节:(
我会将此作为注释,但随后我无法在其中提供可读格式的代码!-)。
Basically, the implication of @GregS's correct answers are that you need to fix one detail in your second implementation:
(I'd make this a comment, but then I couldn't have readably formatted code in it!-).