RangeError: bignum too big to convert into `long'

人走茶凉 提交于 2019-12-23 00:46:12

问题


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

When i am running this code in irb the following error message is the output. and when i compiled the same logic in python it is working absolutely fine. I have Googled "RangeError: bignum too big to convert into `long': but didn't find the relevant answer. Please help me :( Thanks in Advance.

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 `'

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/10024212/rangeerror-bignum-too-big-to-convert-into-long

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