Python | Ways to convert hex into binary
Last Updated :
25 Mar, 2023
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
Python3
ini_string = "1a"
scale = 16
print ( "Initial string" , ini_string)
res = bin ( int (ini_string, scale)).zfill( 8 )
print ( "Resultant string" , str (res))
|
Output
Initial string 1a
Resultant string 00b11010
Method #2: Using Naive Method
Python3
import math
ini_string = "1a"
print ( "Initial string" , ini_string)
n = int (ini_string, 16 )
bStr = ''
while n > 0 :
bStr = str (n % 2 ) + bStr
n = n >> 1
res = bStr
print ( "Resultant string" , str (res))
|
Output
Initial string 1a
Resultant string 11010
Method #3: Using .format
Python3
import math
ini_string = "1a"
print ( "Initial string" , ini_string)
res = "{0:08b}" . format ( int (ini_string, 16 ))
print ( "Resultant string" , str (res))
|
Output
Initial string 1a
Resultant string 00011010
Method #4:Using a loop:
Approach:
- Convert the hexadecimal number to a string
- Initialize an empty string to store the binary representation
- Loop over the hexadecimal digits from the second character to the end
- Convert each hexadecimal digit to its binary representation using a dictionary
- Append the binary representation to the binary string
- Return the binary string
Python3
hex_num = '1f'
hex_dict = { '0' : '0000' , '1' : '0001' , '2' : '0010' , '3' : '0011' , '4' : '0100' , '5' : '0101' , '6' : '0110' , '7' : '0111' , '8' : '1000' , '9' : '1001' , 'a' : '1010' , 'b' : '1011' , 'c' : '1100' , 'd' : '1101' , 'e' : '1110' , 'f' : '1111' }
binary = ''
for digit in hex_num:
binary + = hex_dict[digit]
print (binary)
|
Time complexity: O(n)
Space complexity: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...