- Python Basic Programs
- Python Program Examples
- Python Print Hello World
- Python Get Input from User
- Python Add Two Numbers
- Add Subtract Multiply Divide
- Python Check Even or Odd
- Python Check Prime or Not
- Python Check Alphabet or Not
- Python Check Vowel or Not
- Python Check Leap Year or Not
- Check Reverse equal Original
- Check Positive Negative Zero
- Python Check Armstrong or Not
- Python Check Palindrome or Not
- Python Check Perfect Number
- Python Find Reverse of Number
- Python Count Digits in Number
- Python Add Digits of Number
- Sum of First and Last Digits
- Python Product of Mid Digits
- Sum of Squares of Digits
- Interchange Digits of Number
- Python Sum of n Numbers
- Python Print ASCII Values
- Python Swap Two Numbers
- Python Swap Two Variables
- Python Fahrenheit to Celsius
- Python Celsius to Fahrenheit
- Python Display Calendar
- Python Days into Years, Weeks
- Find Largest of Two Number
- Find Largest of Three Number
- Python Print Fibonacci Series
- Generate Armstrong Numbers
- Python Make Simple Calculator
- Python Add Binary Numbers
- Binary Number Multiplication
- Python Mathematical Programs
- Find Sum of Natural Numbers
- Find Average of n Numbers
- Python Print Multiplication Table
- Print Table using Recursion
- Python Find Average Percentage
- Python Find Grade of Student
- Find Square Root of Number
- Python Print Prime Numbers
- Find Numbers Divisible by
- Python Find Factors of Number
- Python Find Factorial of a Number
- Python Find HCF & LCM
- Python Kilometres to Miles
- Python Find Area of Square
- Python Find Area of Rectangle
- Python Find Area of Triangle
- Python Find Area of Circle
- Python Find Perimeter of Square
- Find Perimeter of Rectangle
- Python Find Perimeter of Triangle
- Find Circumference of Circle
- Python Simple Interest
- Python Solve Quadratic Equation
- Python Different Set of Operations
- Python Display Powers of 2
- Python Find nCr & nPr
- Python Pattern Programs
- Python Print Pattern Programs
- Python Print Diamond Pattern
- Python Print Floyd's Triangle
- Python Print Pascal's Triangle
- Python List Programs
- Python Count Even/Odd in List
- Python Positive/Negative in List
- Python Even Numbers in List
- Python Odd Numbers in List
- Python Sum of Elements in List
- Sum of Odd/Even Numbers
- Python Element at Even Position
- Python Element at Odd Position
- Python Search Element in List
- Python Largest Number in List
- Python Smallest Number in List
- Python Second Largest in List
- Python Second Smallest in List
- Python Insert Element in List
- Python Delete Element from List
- Python Multiply Numbers in List
- Swap Two Elements in List
- Python 1D Array Program
- Python Linear Search
- Python Binary Search
- Python Insertion Sort
- Python Bubble Sort
- Python Selection Sort
- Remove Duplicates from List
- Python Reverse a List
- Python Merge Two List
- Python Copy a List
- Python Conversion Programs
- Python Decimal to Binary
- Python Decimal to Octal
- Python Decimal to Hexadecimal
- Python Binary to Decimal
- Python Binary to Octal
- Python Binary to Hexadecimal
- Python Octal to Decimal
- Python Octal to Binary
- Python Octal to Hexadecimal
- Python Hexadecimal to Decimal
- Python Hexadecimal to Binary
- Python Hexadecimal to Octal
- Python Matrix Programs
- Python Add Two Matrices
- Python Subtract Two Matrices
- Python Transpose Matrix
- Python Multiply Matrices
- Python String Programs
- Python Print String
- Python Find Length of String
- Python Compare Two Strings
- Python Copy String
- Python Concatenate String
- Python Reverse a String
- Python Swap Two Strings
- Python Uppercase to Lowercase
- Python Lowercase to Uppercase
- Python Check Substring in String
- Python Count Character in String
- Count Repeated Characters
- Python Count Word in Sentence
- Python Count Each Vowels
- Python Capitalize Character
- Python Capitalize Word in String
- Python Smallest/Largest Word
- Remove Spaces from String
- Remove Duplicate Character
- Remove Vowels from String
- Remove Punctuation from String
- Python Remove Word in String
- Python Remove Duplicate Words
- WhiteSpace to Hyphens
- Replace Vowels with Character
- Replace Character in String
- Python Sort String in Alphabetical
- Sort Word in Alphabetical Order
- Extract Number from String
- Python Check Anagram Strings
- Python File Programs
- Python Read a File
- Python Write to File
- Python Append Text to File
- Python Copy Files
- Python Merge Two Files
- Python Counts Characters in File
- Python Count Words in File
- Python File Content in Reverse
- Python Lines Contains String
- Python Delete Line from File
- Python Capitalize Word in File
- Python Replace Text in File
- Replace Specific Line in File
- Python Find Size of File
- Python List Files in Directory
- Python Delete Files
- Python Misc Programs
- Python Reverse a Tuple
- Python Merge Two Dictionary
- Python bytes to String
- Python bytearray to String
- Generate Random Numbers
- Python Print Address of Variable
- Python Print Date and Time
- Python Get IP Address
- Python Shutdown/Restart PC
- Python Tutorial
- Python Tutorial
- Give Online Test
- All Test List
- Python Online Test

# Python Program to Convert Hexadecimal to Binary

In this article, we've created some programs in Python, to convert hexadecimal number entered by user to its equivalent binary value. Here are the list of programs:

- Hexadecimal to Binary using
**while Loop** - Using
**int()**and**bin()**Methods - Using user-defined Function
- Using Class

**Note - **Before creating these programs, if you're not aware about steps used for the conversion, then refer
to Hexadecimal to Binary Steps, Formula, Example
to get every required things about the topic.

## Hexadecimal to Binary using while Loop

To convert hexadecimal to binary number in Python, you have to ask from user to enter the hexadecimal number, then convert that number into its equivalent binary value as shown in the program given below:

print("Enter the Hexadecimal Number: ") hexdecnum = input() binnum = "" hexlen = len(hexdecnum) i = 0 while i<hexlen: if hexdecnum[i] == '0': binnum = binnum + "0000" elif hexdecnum[i] == '1': binnum = binnum + "0001" elif hexdecnum[i] == '2': binnum = binnum + "0010" elif hexdecnum[i] == '3': binnum = binnum + "0011" elif hexdecnum[i] == '4': binnum = binnum + "0100" elif hexdecnum[i] == '5': binnum = binnum + "0101" elif hexdecnum[i] == '6': binnum = binnum + "0110" elif hexdecnum[i] == '7': binnum = binnum + "0111" elif hexdecnum[i] == '8': binnum = binnum + "1000" elif hexdecnum[i] == '9': binnum = binnum + "1001" elif hexdecnum[i] == 'a' or hexdecnum[i] == 'A': binnum = binnum + "1010" elif hexdecnum[i] == 'b' or hexdecnum[i] == 'B': binnum = binnum + "1011" elif hexdecnum[i] == 'c' or hexdecnum[i] == 'C': binnum = binnum + "1100" elif hexdecnum[i] == 'd' or hexdecnum[i] == 'D': binnum = binnum + "1101" elif hexdecnum[i] == 'e' or hexdecnum[i] == 'E': binnum = binnum + "1110" elif hexdecnum[i] == 'f' or hexdecnum[i] == 'F': binnum = binnum + "1111" i = i+1 print("\nEquivalent Binary Value: ", binnum)

Here is its sample run:

Now supply the input say **1D4** as hexadecimal number and press `ENTER`

key to convert and print
its equivalent binary value as shown in the snapshot given below:

The dry run of above program with hexadecimal number input **1D4** goes like:

- Initial values,
**hexdecnum=1D4**(entered by user),**i=0**,**binnum=""** - The
**len()**method is used to find length of string. Therefore using the following statement:

`hexlen = len(hexdecnum)`

the value**3**(length of**1D4**or**hexdecnum**) gets initialized to**hexlen** - Now the condition (of
**while loop**)**i<hexlen**or**0<3**evaluates to be true, therefore program flow goes inside the loop - Inside the loop, I've applied
**if-elif**statements of Python to compare the value stored in**hexdecnum**one by one to do the task as per current value - That is, inside the loop, the first condition or condition of
**if**gets evaluated. Since the condition,**hexdecnum[i] == '0'**or**hexdecnum[0] == '0'**or**'1' == '0'**evaluates to be false, therefore program flow does not goes inside this**if**'s body, rather it goes and evaluates the condition of first**elif** - That is, the condition
**hexdecnum[i] == '1'**or**hexdecnum[0] == '1'**or**'1' == '1'**evaluates to be true, therefore program flow goes inside this**elif**'s body, and**binnum + "0001"**or**"" + "0001"**or**"0001"**gets initialized to**binnum** - And the value of
**i**gets incremented by 1. So**i=1** - Now program flow goes back and evaluates the condition of
**while loop**again with new value of**i** - That is, the condition
**i<hexlen**or**1<3**evaluates to be true again, therefore program flow goes inside the loop again. This process continues until the condition evaluates to be false - In this way, the value entered in hexadecimal, gets converted into its equivalent binary value using string
- Therefore, after exiting from the loop, just print the value of
**binnum**as binary equivalent of given hexadecimal number by user at run-time

#### Modified Version of Previous Program

This program uses **end=** to skip printing of an automatic newline using **print()**. In this program,
I've also added an **else** part to handle the thing when all conditions evaluates to be false.

Inside **else**, I've assigned 1 to **chk** and using **break** keyword, the remaining execution of **while**
loop gets skipped. And after exiting from the loop, either by evaluating its condition as false, or by using **break**
keyword, I've checked the value of **chk**. That is, if it equal to 0 (initial value), then program flow never goes
to **else**'s body. Means, no any invalid **hex** digit was entered by user. Otherwise print a message like
**invalid input** as shown in the program given below:

print("Enter the Hexadecimal Number: ", end="") hnum = input() bnum = "" chk = 0 hlen = len(hnum) i = 0 while i<hlen: if hnum[i] == '0': bnum += "0000" elif hnum[i] == '1': bnum += "0001" elif hnum[i] == '2': bnum += "0010" elif hnum[i] == '3': bnum += "0011" elif hnum[i] == '4': bnum += "0100" elif hnum[i] == '5': bnum += "0101" elif hnum[i] == '6': bnum += "0110" elif hnum[i] == '7': bnum += "0111" elif hnum[i] == '8': bnum += "1000" elif hnum[i] == '9': bnum += "1001" elif hnum[i] == 'a' or hnum[i] == 'A': bnum += "1010" elif hnum[i] == 'b' or hnum[i] == 'B': bnum += "1011" elif hnum[i] == 'c' or hnum[i] == 'C': bnum += "1100" elif hnum[i] == 'd' or hnum[i] == 'D': bnum += "1101" elif hnum[i] == 'e' or hnum[i] == 'E': bnum += "1110" elif hnum[i] == 'f' or hnum[i] == 'F': bnum += "1111" else: chk = 1 break i = i+1 if chk==0: print("\nEquivalent Binary Value = ", bnum) else: print("\nInvalid Input!")

Here is its sample run with hexadecimal input **24YD**:

**Note - **Since **Y** is not a valid **hex** digit, therefore the above output, **Invalid Input** was produced.

## Hexadecimal to Binary using int() and bin()

This program uses **int()** and **bin()** methods to do the same job in more precised code as Python known for.

print("Enter the Hexadecimal Number: ", end="") hnum = input() hnum = int(hnum, 16) bnum = bin(hnum) print("\nEquivalent Binary Value = ", bnum)

Here is its sample run with user input, **1DF3** as hexadecimal number input:

**Note - **To print only binary value, that is to skip first two characters from the above output, put
**[2:]** just after the **bnum** variable while printing. That is, replace the following statement:

print("\nEquivalent Binary Value = ", bnum)

with the statement given below:

print("\nEquivalent Binary Value = ", bnum[2:])

Now the output looks like:

## Hexadecimal to Binary using Function

This program is created using user-defined and predefined functions. The name of user-defined function used in this program is
**HexToBin()**. This function receives a value as its argument and returns its equivalent binary value using **bin()** and **int()** method.

def HexToBin(h): return bin(int(h, 16)) print("Enter the Hexadecimal Number: ", end="") hnum = input() bnum = HexToBin(hnum) print("\nEquivalent Binary Value = ", bnum[2:])

## Hexadecimal to Binary using Class

This is the last program of this article, created using a class named **CodesCracker**, an object-oriented feature of Python.

class CodesCracker: def HexToBin(self, h): return bin(int(h, 16)) print("Enter the Hexadecimal Number: ", end="") hnum = input() obj = CodesCracker() bnum = obj.HexToBin(hnum) print("\nEquivalent Binary Value = ", bnum[2:])

In this program, an object named **obj** of class **CodesCracker** is created to access its member function
named **HexToBin()** using **dot (.)** operator. Rest of the things works like a normal function.

#### Same Program in Other Languages

- Java Convert Hexadecimal to Binary
- C Convert Hexadecimal to Binary
- C++ Convert Hexadecimal to Binary

« Previous Program Next Program »

Follow/Like Us on Facebook

Subscribe Us on YouTube