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

Pab*_*abi -1 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
Run Code Online (Sandbox Code Playgroud)

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

你数 0、1,然后你必须从零开始并添加一列!下一列的价值是第一列的两倍。由于二进制是基数为 2 的系统,因此每个数字代表 2 的幂,最右边的数字代表 20 (0),下一个代表 21 (2),然后是 22 (4)、23 (8),依此类推。

Oce*_*uto 5

Float,就像 ruby​​ 一样,没有二进制表示。如果您想在基数之间进行转换,您可以通过将基数作为参数传入来使用 to_s。

21.to_s(2) #-> 10101
Run Code Online (Sandbox Code Playgroud)