转换后我需要对它执行一些操作(例如,添加)。另外,我需要以指定的宽度打印结果。
为了实现上述目的,我写了以下代码:
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:
n1 = int(input("Enter a decimal number: "))
n2 = int(input("Enter a decimal number: "))
# type cast to 'int' is done to provide width
binaryN1 = int("{0:b}".format(n1))
binaryN2 = int("{0:b}".format(n2))
binarySum = int("{0:b}".format(n1 + n2))
width = (n1 + n2).bit_length()
print("max width = {}".format(width))
print ("{0:0{3}} + {1:0{3}} = {2:0{3}}".format(binaryN1, binaryN2, binarySum, width))
print ("{0} + {1} = {2}".format(type(binaryN1), type(binaryN2), type(binarySum)))
有什么想知道还有其他(更好)的方法吗?我知道可以使用bin()
函数,但是它返回一个字符串,所以我不能对它执行(整数)操作。
此外,任何评论意见改进代码将非常感激,因为我是Python的初学者。
答案 0 :(得分:0)
这似乎正在做我想做的事情。以下代码是根据问题中提供的原始代码构建的,其中包含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))