2012-04-05 95 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

相關問題