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

当我在irb中运行此代码时,以下错误消息是输出。当我在python中编译相同的逻辑时,它工作得很好。我用Google搜索“的RangeError:BIGNUM太大而转换成'长':但是没有找到相关的答案 请帮我:(在此先感谢RangeError:bignum太大,无法转换为'long'

 
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

正如我下面所说的,Ruby有'num.to_i(2)'形式的这种内置形式:-) – 2012-04-05 07:55:30

回答

2

试试这个

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 
。 。
+0

非常感谢!工作! :D – aahlad 2012-04-05 07:53:40

4

你得到的与num[n]是一个字符串,而不是一个号码,我改写了你的代码更地道红宝石,这是它会是什么样子:

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

然而,最习惯的可能是num.to_i(2),因为我看到它正在尝试从二进制转换为十进制,这正是这样做的。

+0

+1 each_char.with_index是一个非常好的模式 - 对我来说是新的,所以谢谢。 – joelparkerhenderson 2012-04-05 07:53:56

+0

请注意,在仅存在'each_with_index'之前,将'.with_index'作为单独的方法添加到1.9中。 – 2012-04-05 07:54:36

+0

+1用于指出内置的转换方法。 – 2012-04-05 07:56:15

相关问题