Open In App

Python – Ways to convert hex into binary

Last Updated : 20 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a hexadecimal number we need to convert it to binary. For example a = “1A3” we need to convert it to binary so that resultant output should be 110100011.

Using bin() and int()

We can convert hexadecimal to binary by first converting it to an integer using int() and then using the bin() function.

Python
a = "1A3"

# Convert hexadecimal to an integer
d = int(a, 16)

# Convert integer to binary using bin()
b = bin(d)[2:]  # Remove the "0b" prefix

print("Binary:", b)  

Output
Binary: 110100011

Explanation:

  • int(a, 16) converts hexadecimal string “1A3” to its equivalent integer value.
  • bin(d)[2:] converts integer to binary and removes “0b” prefix to get final binary representation.

Using format()

format() function allows us to convert a number to binary without the “0b” prefix.

Python
a = "1A3"

# Convert to binary using format()
b = format(int(a, 16), 'b')

print("Binary:", b)  

Output
Binary: 110100011

Explanation:

  • int(a, 16) converts the hexadecimal string “1A3” to its corresponding integer value.
  • format(int(a, 16), ‘b’) converts integer to a binary string without “0b” prefix providing binary representation directly


Article Tags :
Practice Tags :

Similar Reads