1

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
  • 1
    kite.com/python/answers/… Commented Feb 9, 2022 at 3:48
  • Show what you tried. Show the "errors". The example you've given shows valid conversions from binary to hex, so it's unclear what the problem is here. Commented Feb 9, 2022 at 3:51
  • don't worry. i solved it. :) Commented Feb 9, 2022 at 4:06

4 Answers 4

2

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'
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1

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)

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.