How to Convert Binary to Hexadecimal Using Python3

How to Convert Binary to Hexadecimal Using Python3

which is the easiest way that i can convert binary number into a hexadecimal number using latest python3?

i tried to convert a binary to number into a hexadecimal using hex() function. but it runs into few errors.

The code that i tried -:

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

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

error that i faced :

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

EXAMPLE-:

  • 111 --> 7
  • 1010101011 --> 2AB
3

4 Answers

Use int to convert a string of digits to an integer. Use hex to convert that integer back to a hex string.

>>> hex(int('111', 2))
'0x7'
>>> hex(int('1010101011', 2))
'0x2ab'
0
# 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)

You may use the Hex inbuilt function of Python 3. you can use this code too.

binary_string = input("enter binary number: ")

decimal_representation = int(binary_string, 2) hexadecimal_string = hex(decimal_representation)

print("your hexadecimal string is: ",hexadecimal_string)

Method:

  • Considering you need '2AB' instead of '0x2ab'.
>>> Hex=lambda num,base:hex(int(num,base))[2:].upper()
>>> Hex('111',2)
'7'
>>> Hex('1010101011',2)
'2AB'
Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.