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 stringini_string = "1a"scale = 16 # Printing initial stringprint ("Initial string", ini_string) # Code to convert hex to binaryres = bin(int(ini_string, scale)).zfill(8) # Print the resultant stringprint ("Resultant string", str(res)) |
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 stringini_string = "1a" # Printing initial stringprint ("Initial string", ini_string) # Code to convert hex to binaryn = int(ini_string, 16) bStr = ''while n > 0: bStr = str(n % 2) + bStr n = n >> 1 res = bStr # Print the resultant stringprint ("Resultant string", str(res)) |
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 stringini_string = "1a" # Printing initial stringprint ("Initial string", ini_string) # Code to convert hex to binaryres = "{0:08b}".format(int(ini_string, 16)) # Print the resultant stringprint ("Resultant string", str(res)) |
Output:
Initial string 1a
Resultant string 00011010


