如何使用 python3 将二进制转换为十六进制

How to convert binary to hexadecimal using python3

这是我可以使用最新的 python3 将二进制数转换为十六进制数的最简单方法?

我尝试使用 hex() 函数将二进制数转换为十六进制数。但它遇到了一些错误。

我试过的代码-:

choice = input("Enter Your Binary Number: ")

def binaryToHex(num):
    answer = hex(num)
    return(num)
    
print(binaryToHex(choice))

我遇到的错误:

Traceback (most recent call last):
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 83, in <module>
    print(binaryToHex(choice))
  File "e:\#Programming\Python\Number System Converter 0.1V\test.py", line 80, in binaryToHex
    answer = hex(num)
TypeError: 'str' object cannot be interpreted as an integer

示例-:

# Python code to convert from Binary
# to Hexadecimal using int() and hex()
def binToHexa(n):
    
    # convert binary to int
    num = int(str(n), 2)
      
    # convert int to hexadecimal
    hex_num = hex(num)
    return(hex_num)

使用int将一串数字转换为整数。使用 hex 将该整数转换回十六进制字符串。

>>> hex(int('111', 2))
'0x7'
>>> hex(int('1010101011', 2))
'0x2ab'

方法:

  • 考虑到您需要 '2AB' 而不是 '0x2ab'
>>> Hex=lambda num,base:hex(int(num,base))[2:].upper()
>>> Hex('111',2)
'7'
>>> Hex('1010101011',2)
'2AB'

你可以使用Python3的Hex内置函数,你也可以使用这个代码。

binary_string = input("输入二进制数:")

decimal_representation = int(binary_string, 2) hexadecimal_string = 十六进制(decimal_representation)

print("你的十六进制字符串是:",hexadecimal_string)