num = "0000001000000000011000000000000010010011000011110000000000000000"
for n in 0...num.length
temp = num[n]
dec = dec + temp*(2**(num.length - n - 1))
end
puts dec
当我在 irb 中运行此代码时,输出以下错误消息。当我在 python 中编译相同的逻辑时,它工作得非常好。我用谷歌搜索了“RangeError: bignum too big to convert into `long': 但没有找到相关的答案。 请帮助我 :( 提前致谢。
RangeError: bignum too big to convert intolong' from (irb):4:in
*' from (irb):4:inblock in irb_binding' from (irb):2:in
each' from (irb):2 from C:/Ruby193/bin/irb:12:in `'
最佳答案
num[n]
得到的是单字符串,而不是数字。我将您的代码重写为更惯用的 Ruby,这就是它的样子:
dec = num.each_char.with_index.inject(0) do |d, (temp, n)|
d + temp.to_i * (2 ** (num.length - n - 1))
end
然而,最惯用的可能是 num.to_i(2)
,因为在我看来,您正在尝试将二进制转换为十进制,而这正是它所做的。
关于ruby - 范围错误 : bignum too big to convert into `long' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10024212/