Hansana Prabath
Hansana Prabath

Reputation: 151

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-:

Upvotes: 1

Views: 2668

Answers (4)

chirag ahir
chirag ahir

Reputation: 11

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)

Upvotes: 1

Bibhav
Bibhav

Reputation: 1767

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'

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308548

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'

Upvotes: 2

Shahriar Zaman
Shahriar Zaman

Reputation: 938

# 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)

Upvotes: 1

Related Questions