📜  将Base 4系统转换为二进制数的Python程序

📅  最后修改于: 2022-05-13 01:54:48.982000             🧑  作者: Mango

将Base 4系统转换为二进制数的Python程序

给定一个基数为 4 的数字 N,任务是编写一个Python程序来打印其二进制等价物。

转换表:

例子:

方法:

  • 取一个空字符串说resultstr。
  • 我们将十进制转换为字符串。
  • 遍历字符串并将每个字符转换为整数
  • 如果整数是1 或 0,则在转换为二进制之前将 '0' 添加到resultsstr (因为我们不能有整数 01,00)
  • 现在将此整数转换为二进制字符串连接生成的二进制字符串 结果
  • resultstr转换为整数(删除前导零)。
  • 返回结果字符串。

下面是上述方法的实现。

Python3
# function which converts decimal to binary
def decToBin(num):
   
    # Using default binary conversion functions
    binary = bin(num)
     
    # removing first two character as the
    # result is always in the form 0bXXXXXXX
    # by taking characters after index 2
    binary = binary[2:]
    return binary
 
# function to convert base4 to binary
def convert(num):
   
    # Taking a empty string
    resultstr = ""
     
    # converting number to string
    numstring = str(num)
     
    # Traversing string
    for i in numstring:
       
        # converting this character to integer
        i = int(i)
         
        # if i is 1 or 0 then add '0' to result
        # string
        if(i == 1 or i == 0):
            resultstr = resultstr+'0'
 
        # passing this integer to get converted to
        # binary
        binary = decToBin(i)
         
        # print(binary)
        # Concatenating this binary string to result
        # string
        resultstr = resultstr+binary
         
    # Converting resultstr to integer
    resultstr = int(resultstr)
     
    # Return result string
    return resultstr
 
 
# Driver code
Number = 11002233
 
# Passing this number to convert function
print(convert(Number))


输出:

101000010101111