Ruby中的位移 [英] Bit shifting in Ruby
问题描述
我目前正在将Visual Basic应用程序转换为Ruby,因为我们正在将其移至Web.但是,在转换某些算法时,我遇到了有关移位的问题.
I'm currently converting a Visual Basic application to Ruby because we're moving it to the web. However when converting some algorithms I've run into a problem concerning bit shifting.
据我所知,问题在于VB对Integer类型执行的大小掩码(如
How I understand it, the problem lies in the size mask VB enforces on Integer types (as explained Here). Ruby, in practice, doesn't differentiate in these types.
那么问题是
Dim i As Integer = 182
WriteLine(i << 24) '-1241513984
Ruby
puts 182 << 24 # 3053453312
我一直在Google上搜索并阅读了过去几个小时的移位信息,但是还没有找到解决此问题的方法或方向.
I've been Googling and reading up on bit shifting the last hours but haven't found a way, or direction even, to tackle this problem.
推荐答案
您需要复制Visual Basic正在做什么,即
You need to replicate what visual basic is doing, namely
- 根据记录屏蔽移位值
- 使用0xFFFFFFFF遮盖结果(因为ruby将为您提升该值到一个大数字
- 如果最高位被设置,则从结果中减去2 ^ 32(因为带符号的整数存储在例如
def shift_32 x, shift_amount shift_amount &= 0x1F x <<= shift_amount x &= 0xFFFFFFFF if (x & (1<<31)).zero? x else x - 2**32 end end
这篇关于Ruby中的位移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!