Question

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

Était-ce utile?

La solution

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top