问题
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 intolong' from (irb):4:in
*' from (irb):4:inblock in irb_binding' from (irb):2:in
each' 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