使用Ruby创建十进制到二进制转换器?

时间:2015-07-09 02:32:50

标签: ruby

我希望创建一个程序,将整数转换为二进制,反之亦然,但我不知道该怎么做或如何解决这个问题。

这是我到目前为止所做的:

#Method that check if string is a number.
def is_number?(string)
  true if Float(string) rescue false
end

#Method to convert decimal to binary
def decimal_to_binary(number)
  if is_number?(number)==false
    return "This method only accepts positive integers."
  elsif number<=0
    return "This method only accepts positive integers."
  else
    return #HERE it needs to converts decimal to binary
  end
end

#Method to convert binary to decimal
def binary_to_decimal(number)
end

以下是对二进制文件的一些解释,以防您不知道/记得:

你算0,1,然后你必须重新开始零并添加一列!下一列的值是第一列的两倍。由于二进制是基础2系统,每个数字代表2的幂,最右边的数字代表20(0),下一个数字代表21(2),然后是22(4),23(8)等等。

1 个答案:

答案 0 :(得分:4)

Float,正如ruby所做的那样,没有二进制表示。如果你想在基数之间进行转换,你可以通过将基数作为参数传递来使用to_s。

21.to_s(2) #-> 10101