[英]Python function to convert Binary digit to Hexadecimal
我有一个将二进制数字转换为十六进制的程序的另一个问题。 我有一个运行良好的程序,但以小写字母显示十六进制数字,尽管答案需要大写,如问题和示例运行所示
这是我的代码
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()
由于这出现了一些 - 这是一个相当 Pythonic 的答案,希望可以作为未来问题的规范参考。
首先,只需将输入保留为字符串:
binary_value = input('Enter a binary number: ')
然后使用base
参数为 2 的内置int
(表示将字符串解释为二进制数字)从字符串中获取整数:
number = int(binary_value, 2)
# 10001111 -> 143
然后,您可以使用f-string
使用格式说明符X
打印您的数字,这意味着“以大写字母和无前缀的十六进制表示”:
print(f'The hex value is {number:X}')
您的整个代码库将类似于(坚持使用两个函数和您的命名约定):
def binaryToHex(binaryValue):
number = int(binaryValue, 2)
return format(number, 'X')
def main():
binaryValue = input('Enter a binary number: ')
print('The hex value is', binaryToHex(binaryValue))
main()
您犯的一个错误是 h1 不存在于代码中,但它存在。
.upper() 将字符串更改为大写
def main():
binaryValue = list(input("Input a binary number: "))
hexval=binaryToHex(binaryValue)
hexa=hexval.upper()
print("The hex value is",hexa[ 2:4]) #strips off the first 2 digits
输出:
Input a binary number: 10001111
The hex value is 8F
只做一个功能...
def binaryToHex():
binval = input('Input a binary number : ')
num = int(binval, base=2)
hexa = hex(num).upper().lstrip('0X')
print(f'The hex value is {hexa}')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.