Ruby 中通过进位左旋转
我正在尝试在 Ruby 中实现 SHA1,为此我需要通过进位执行左旋转。我编写的代码似乎可以工作 1 轮,但超过 1 轮后它就无法通过我的测试,有人知道为什么吗?
class Integer
def rotate_left(count, size)
temp = self
count.times do
first_bit = (self & 2 ** size)[size]
temp = temp << 1
temp = temp ^ first_bit
temp = temp ^ (2 ** (size + 1))
end
return temp
end
end
I'm trying to implement SHA1 in Ruby and in order to do so I need to preform a left rotate through carry. The code I've written seems to work for 1 rotation, but any more than that it fails my tests, anybody know why?
class Integer
def rotate_left(count, size)
temp = self
count.times do
first_bit = (self & 2 ** size)[size]
temp = temp << 1
temp = temp ^ first_bit
temp = temp ^ (2 ** (size + 1))
end
return temp
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我首先检查了 Wikipedia 以确保我理解该操作。看起来你好像失去了你的随身物品。另外,我添加了测试类以确保我得到正确的答案。我不确定您是否想保留进位,因此我注释掉了代码以截断结果。希望这有帮助!
I checked Wikipedia first to make sure I understood the operation. It looks as if you were losing your carry's. Also, I added the test class to make sure I was getting the right answers. I wasn't sure if you wanted to preserve the carried bits or not so I commented out the code to truncate the result. Hope this helps!
您使用什么来确定
尺寸
?例如,如果您尝试进行 4 位旋转,并且将大小设置为 4,则first_bit 计算将获取第 5 位:因此索引正常。但在内循环中,您从
self
获取first_bit,而不是temp。所以这只会在第一次时有效。what are you using for
size
? If you are trying to do a 4 bit rotation for example, and you set size to 4, then the first_bit calculation is getting the 5th bit:So the indexing is Ok. But in the inner loop, you are getting first_bit from
self
instead of temp. So this will only work the 1st time through.我曾经在Ruby中实现了 SHA-256 (使用右旋转)并最终使用这段代码:
您可以将其修改为左旋转:
虽然很难理解......但它有效:)
I once implemented SHA-256 in Ruby (which is using right rotate) and finally used this code:
You can modify it for left rotate:
Although it's very hard to understand... it works :)