2011-04-24 224 views
20

嘗試在Ruby中使用基礎...我已經佈置的代碼看起來很重複。還有更好的方法嗎?轉換十六進制,十進制,八進制和ASCII?

module Converter 
    def self.convert(value, from, to) 
    case from 
    when :hex 
     case to 
     when :dec 
     # code to change hex to dec 
     when :oct 
     # code to change hex to oct 
     when :bin 
     # code to change hex to bin 
     when :ascii 
     # code to change hex to ascii 
     end 
    when :dec 
     case to 
     when :hex 
     # code to change dec to hex 
     when :oct 
     # code to change dec to oct 
     when :bin 
     # code to change dec to bin 
     when :ascii 
     # code to change dec to ascii 
     end 
    when :oct 
     case to 
     when :hex 
     # code to change oct to hex 
     when :dec 
     # code to change oct to dec 
     when :bin 
     # code to change oct to bin 
     when :ascii 
     # code to change oct to ascii 
     end 
    when :bin 
     case to 
     when :hex 
     # code to change bin to hex 
     when :dec 
     # code to change bin to dec 
     when :oct 
     # code to change bin to oct 
     when :ascii 
     # code to change bin to ascii 
     end 
    when :ascii 
     case to 
     when :hex 
     # code to change ascii to hex 
     when :dec 
     # code to change ascii to dec 
     when :oct 
     # code to change ascii to oct 
     when :bin 
     # code to change ascii to bin 
     end 
    end 
    end 
end 
+0

convert需要字符串和返回字符串,對吧?你能舉一些例子嗎?例如,十六進制是「0xXX」? – tokland 2011-04-24 20:54:11

回答

74
class String 
    def convert_base(from, to) 
    self.to_i(from).to_s(to) 
    # works up-to base 36 
    end 
end 

p '1010'.convert_base(2, 10) #=> "10" 
p 'FF'.convert_base(16, 2) #=> "11111111" 
+2

天才。謝謝。 – RyanScottLewis 2011-04-24 21:25:12

3

拿出代碼將任何東西轉換爲小數,從小數轉換爲任何東西,然後再合併它們。例如。將二進制轉換爲十六進制,先轉換爲十進制,然後轉換爲十六進制。給定它使用的一組數字,基本轉換也可以通用的方式實現,可以處理任何基數。另外,請記住,內存中的一個數值並沒有真正的基本概念(很明顯,它被表示爲二進制),但這大多是不相關的)。這只是一個價值。只有當你涉及到字符串時,基礎纔會變得非常重要。所以如果你的「小數」真的意味着一個數字值而不是一串數字,最好不要把它稱爲「小數」。

2

我不同意使用String類來操作二進制數據。 使用Fixnum似乎更合適,因爲該類中有按位運算符。 當然,String類具有帶「ENV」的字符串#to_s,並會將整數更改爲新的基數,我們正在此處使用數字。 但這只是恕我直言。 其他的好答案。

這是我的Fixnum使用示例。

class Fixnum 
    def convert_base(to) 
    self.to_s(to).to_i 
    end 
end 

p '1010'.to_i(2).convert_base(10) #=> 10 real numbers 
p 'FF'.hex.convert_base(2)  #=> 11111111 
p 72.convert_base(16)    #=> 48