Search code examples
rubyirbbignum

RangeError: bignum too big to convert into `long'


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


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