RangeError: bignum too big to convert into `long'

大城市里の小女人 提交于 2019-12-06 14:38:34

Try this

num = "0000001000000000011000000000000010010011000011110000000000000000"
dec = 0
for n in 0...num.length 
   temp = num[n] 
   dec =  dec + temp.to_i * (2**(num.length - n - 1))
end
puts dec

What you get with num[n] is a one character string, not a number. I rewrote your code to more idiomatic Ruby, this is how it would look like:

dec = num.each_char.with_index.inject(0) do |d, (temp, n)| 
  d + temp.to_i * (2 ** (num.length - n - 1))
end

The most idiomatic however would probably be num.to_i(2), because as I see it you are trying to convert from binary to decimal, which is exactly what this does.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!