Python函数将二进制数字转换为十六进制

2024-10-03 19:29:16 发布

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

我有另一个问题的程序,转换成十六进制二进制数字。我有一个运行良好的程序,但是用小写字母显示十六进制数字,尽管答案必须是大写字母,如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()

This is what is displayed when I run


Tags: torun程序convertismaindef数字
3条回答

既然这是一个公平点-这里有一个答案,这是相当python和希望作为一个规范的参考未来的问题。你知道吗

首先,将输入保持为字符串:

binary_value = input('Enter a binary number: ')

然后使用内置的intbase参数2(表示将字符串解释为二进制数字)从字符串中获取整数:

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}')

相关问题 更多 >