Python | Ways to convert hex into binary
Conversion of hex to binary is a very common programming question. In this article, we will see a few methods to solve the above problem.
Method #1: Using bin and zfill
# Python code to demonstrate # conversion of a hex string # to the binary string # Initialising hex string ini_string = "1a"scale = 16 # Printing initial string print ("Initial string", ini_string) # Code to convert hex to binary res = bin(int(ini_string, scale)).zfill(8) # Print the resultant string print ("Resultant string", str(res)) |
chevron_right
filter_none
Output:
Initial string 1a
Resultant string 00b11010
Method #2: Using Naive Method
# Python code to demonstrate # conversion of hex string # to binary string import math # Initialising hex string ini_string = "1a" # Printing initial string print ("Initial string", ini_string) # Code to convert hex to binary n = int(ini_string, 16) bStr = '' while n > 0: bStr = str(n % 2) + bStr n = n >> 1 res = bStr # Print the resultant string print ("Resultant string", str(res)) |
chevron_right
filter_none
Output:
Initial string 1a
Resultant string 11010
Method #3: Using .format
# Python code to demonstrate # conversion of hex string # to binary string import math # Initialising hex string ini_string = "1a" # Printing initial string print ("Initial string", ini_string) # Code to convert hex to binary res = "{0:08b}".format(int(ini_string, 16)) # Print the resultant string print ("Resultant string", str(res)) |
chevron_right
filter_none
Output:
Initial string 1a
Resultant string 00011010
Recommended Posts:
- Python | Ways to convert Boolean values to integer
- Python | Ways to convert list of ASCII value to string
- Python | Ways to convert string to json object
- Python | Convert String to Binary
- Python program to convert floating to binary
- Python | Ways to convert array of strings to array of floats
- Python program to convert decimal to binary number
- Python | Ways to Convert a 3D list into a 2D list
- Python | Ways to split a string in different ways
- Python | Convert list to Python array
- Different ways to clear a list in Python
- Python | Ways to concatenate tuples
- Python | Ways to flatten a 2D list
- Python | Different ways to kill a Thread
- Print lists in Python (4 Different Ways)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



