'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
Solution 1:[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)
Solution 2:[2]
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)
Solution 3:[3]
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'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | philoopher97 |
| Solution 2 | chirag ahir |
| Solution 3 | Bibhav |
