ruby - 范围错误 : bignum too big to convert into `long'

标签 ruby irb bignum

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 into long'
        from (irb):4:in*'
        from (irb):4:in block in irb_binding'
        from (irb):2:ineach'
        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/

相关文章:

c - 使用 GMP 计算 bignum 的平方根

python - 为什么对于非常大的数字,除法会变得更快

javascript - 用于网络浏览器的 Ruby 插件?

ruby - 为什么当前目录不在我的 Ruby 路径中?

ruby - 如何格式化 irb 命令提示符

perl - 如何从 Perl bignum 中获取数字?

Rubygame 不工作 : 'load_library' : Could not load SDL

python - 是否有 Ruby/Python HTML 重排/布局库?

ruby - Ruby 中 DateTime.parse 中的 PST/PDT

ruby 1.9.2 : irb throws ArgumentError: invalid byte sequence in UTF-8 when entering German Umlaut