使用最新的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
例子
发布于 2022-02-09 03:55:38
使用int
将数字字符串转换为整数。使用hex
将该整数转换回十六进制字符串。
>>> hex(int('111', 2))
'0x7'
>>> hex(int('1010101011', 2))
'0x2ab'
发布于 2022-02-09 03:54:49
# 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)
发布于 2022-02-09 04:14:41
您可以使用Python 3的十六进制内置函数。您也可以使用这段代码。
binary_string =输入(“输入二进制数字:")
decimal_representation = int(binary_string,2) hexadecimal_string =十六进制(Decimal_representation)
打印(“您的十六进制字符串是:",hexadecimal_string)
https://stackoverflow.com/questions/71043763
复制相似问题