Python中十进制到二进制的转换和viceversa

2024-10-02 06:38:22 发布

您现在位置:Python中文网/ 问答频道 /正文

  1. 给定一个十进制数,我需要把它转换成二进制
  2. 给定一个二进制数,我需要把它转换成十进制数

转换之后,我需要对它执行一些操作(例如,加法)。我还需要打印指定宽度的结果。在

为了完成上述任务,我编写了以下代码:

Binary-Decimal:

    n1 = int(input("Enter a binary number: "))
    n2 = int(input("Enter a binary number: "))

    # type cast to 'int' is done to provide width
    decimalN1 = int("{0:d}".format(n1), 2)
    decimalN2 = int("{0:d}".format(n2), 2)
    decimalSum = int("{0:d}".format(n1 + n2), 2)

    width = len(str(decimalSum))
    print("max width = {}".format(width))

    print ("{0:0{3}} + {1:0{3}} = {2:0{3}}".format(decimalN1, decimalN2, decimalSum, width))
    print ("{0} + {1} = {2}".format(type(decimalN1), type(decimalN2), type(decimalSum)))

Decimal-Binary:

^{pr2}$

你想知道有没有其他更好的方法?我知道可以使用bin()函数,但是它返回一个字符串,所以我不能对它执行(integer)操作。在

另外,如果有任何评论可以改进代码,我将非常感激,因为我是Python的初学者。在


Tags: 代码formatinputtype二进制widthintdecimal
1条回答
网友
1楼 · 发布于 2024-10-02 06:38:22

这似乎是在做我想做的事。下面的代码是根据我在问题中给出的原始代码构建的,建议来自Code Review。在

#!/usr/bin/python3

# this function accepts a decimal integer and returns a binary string
def decimalToBinary (decimalInt) :
    return "{0:b}".format (decimalInt)
# this function accepts a binary string and returns a decimal integer
def binaryToDecimal (binaryString) :
    return int (binaryString, 2)

x = int (input ("Enter a decimal number: "))
y = int (input ("Enter a decimal number: "))
sumInDecimal = x + y
print ("{0} when converted to binary is {1}".format (x, decimalToBinary(x)))
print ("{0} when converted to binary is {1}".format (y, decimalToBinary(y)))
print ("Addition in base 10: \t {0} + {1} = {2}".format (x, y, x + y))
print ("Addition in base  2: \t {0} + {1} = {2}".format (decimalToBinary(x), decimalToBinary(y), decimalToBinary(sumInDecimal)))
print ()
x = input ("Enter a binary number: ")
y = input ("Enter a binary number: ")
# convert binary to decimal before any operation, the result of the operation will be in decimal
sumInDecimal = binaryToDecimal(x) + binaryToDecimal(y)
print ("{0} when converted to decimal is {1}".format (x, binaryToDecimal(x)))
print ("{0} when converted to decimal is {1}".format (y, binaryToDecimal(y)))
print ("Addition in base  2: \t {0} + {1} = {2}".format (x, y, decimalToBinary(sumInDecimal)))
print ("Addition in base 10: \t {0} + {1} = {2}".format (binaryToDecimal(x), binaryToDecimal(y), sumInDecimal))

相关问题 更多 >

    热门问题