我有另一个问题的程序,转换成十六进制二进制数字。我有一个运行良好的程序,但是用小写字母显示十六进制数字,尽管答案必须是大写字母,如question and sample run所示
这是我的密码
def binaryToHex(binaryValue):
#convert binaryValue to decimal
decvalue = 0
for i in range(len(binaryValue)):
digit = binaryValue.pop()
if digit == '1':
decvalue = decvalue + pow(2, i)
#convert decimal to hexadecimal
hexadecimal=hex(decvalue)
return hexadecimal
def main():
binaryValue = list(input("Input a binary number: "))
hexval=binaryToHex(binaryValue)
hexa=h1.capitalize() #Tried to use capitalize() function but didn't worl
print("The hex value is",hexa[ 2:4]) #strips off the first 2 digits
main()
既然这是一个公平点-这里有一个答案,这是相当python和希望作为一个规范的参考未来的问题。你知道吗
首先,将输入保持为字符串:
然后使用内置的
int
和base
参数2(表示将字符串解释为二进制数字)从字符串中获取整数:然后您可以使用
f-string
来打印带有格式说明符X
的数字,格式说明符的意思是“带大写字母和无前缀的十六进制”:您的整个代码库将是这样的(坚持两个函数和命名约定):
您犯的一个错误是h1在代码中不存在,但它仍然存在。你知道吗
.upper()将字符串更改为大写
输出:
只做一个函数。。。你知道吗
相关问题 更多 >
编程相关推荐