尝试在Ruby中来回移动...我列出的代码似乎非常重复。有没有更好的方法?
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发布于 2011-04-25 05:10:28
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"发布于 2011-04-25 03:59:36
想出代码把任何东西转换成十进制,从十进制转换成任何东西,然后把它们组合起来。例如,要从二进制转换为十六进制,先转换为十进制,然后再转换为十六进制。基数转换也很容易以一种通用的方式实现,它可以处理任何基数,因为它使用了一组数字。
此外,请记住,内存中的数值实际上并不具有基数的概念(显然,它被表示为二进制,但这几乎是无关紧要的)。这只是一个值。只有当你得到字符串的时候,bases才变得真正有意义。因此,如果您的"decimal“实际上是指一个数值而不是一串数字,那么最好不要称它为"decimal”。
发布于 2013-02-01 01:46:10
我不同意使用String类来操作二进制数据。使用Fixnum似乎更合适,因为该类中有按位运算符。当然,String类具有带有"ENV“的String#to_s,并且会将一个Integer更改为一个新的基数,10.to_s(16)我们在这里使用的数字。但那只是IMHO。反之,答案很好。
以下是我对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) #=> 48https://stackoverflow.com/questions/5772875
复制相似问题