- 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
Python Program to Convert Hexadecimal to Decimal
In this article, I've created some programs in Python, to convert hexadecimal number entered by user at run-time to its equivalent decimal value. Here are the list of programs:
- Hexadecimal to Decimal using while Loop
- Using int() Method
- 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 Decimal Steps, Formula, Example to get every required things about the topic.
Hexadecimal to Decimal using while Loop
To convert hexadecimal to decimal number in Python, you have to ask from user to enter a hexadecimal number, then convert that number into its equivalent decimal value as shown in the program given below:
print("Enter the Hexadecimal Number: ") hexdecnum = input() chk = 0 decnum = 0 hexdecnumlen = len(hexdecnum) hexdecnumlen = hexdecnumlen-1 i = 0 while hexdecnumlen>=0: rem = hexdecnum[hexdecnumlen] if rem>='0' and rem<='9': rem = int(rem) elif rem>='A' and rem<='F': rem = ord(rem) rem = rem-55 elif rem>='a' and rem<='f': rem = ord(rem) rem = rem-87 else: chk = 1 break decnum = decnum + (rem * (16 ** i)) hexdecnumlen = hexdecnumlen-1 i = i+1 if chk == 0: print("\nEquivalent Decimal Value: ", decnum) else: print("\nInvalid Input!")
Here is its sample run:
Now supply the input say 4A7F as hexadecimal number and press ENTER
key to convert and print
its equivalent decimal value as shown in the snapshot given below:
Note - The len() method is used to find length of a string. That is, this method returns length of string passed as its argument.
Note - The ord() method is used to find Unicode of a character passed as its argument. For example, ord('A') returns 65, ord('B') returns 66, ord('c') returns 99 etc.
Note - The ** is used to calculate value of a number to any power. For example num ** i gets treated as numi. That is, 16 ** 3 returns the value of 163, which will be 16*16*16 or 4096
The dry run of above program with user input 4A7F goes like:
- Initial values, hexdecnum=4A7F (entered by user), chk=0, decnum=0, hexdecnumlen=4 (length of hexdecnum or 4A7F), i=0
- Since the value of hexdecnumlen is decremented by 1. Therefore hexdecnumlen=3
- Now the condition (of while loop) hexdecnumlen>=0 or 3>=0 evaluates to be true, therefore program flow goes inside the loop
- hexdecnum[hexdecnumlen] or hexdecnum[3] or 'F' (last index's character of hexdecnum) gets initialized to rem
- Since rem's value is 'F', therefore the the condition of first elif (that is rem>='A' and rem<='F') evaluates to be true, therefore program flow goes inside its body and ord(rem) or ord('F') or 70 gets initialized to rem. And using the second statement, rem-55 or 70-55 or 15 (15 corresponds to 'F' in hexadecimal number system) initialized to rem
- Now decnum + (rem * (16 ** i)) or 0 + (15 * (160)) or 15 * 1 or 15 gets initialized to decnum
- hexdecnumlen-1 or 3-1 or 2 gets initialized to hexdecnumlen
- i+1 or 0+1 or 1 gets initialized to i
- Now program flow goes back and evaluates the condition of while loop again with new value of hexdecnumlen
- That is, the condition hexdecnumlen>=0 or 2>=0 evaluates to be true again, therefore program flow goes inside the loop. This process continues until the condition evaluates to be false
- In this way, the given number (in hexadecimal) gets converted into its equivalent decimal value
- So after exiting from the loop, print the value of decnum, if chk's value is equal to 0 (initial value)
- And if chk's value is not equal to 0 (its initial value), means that program flow goes inside the else's body once. And that means, an invalid hex digit was entered by user
Modified Version of Previous Program
This program uses end= to skip printing of an automatic newline using print()
print("Enter Hexadecimal Number: ", end="") hnum = input() chk = dnum = i = 0 hlen = len(hnum) - 1 while hlen>=0: if hnum[hlen]>='0' and hnum[hlen]<='9': rem = int(hnum[hlen]) elif hnum[hlen]>='A' and hnum[hlen]<='F': rem = ord(hnum[hlen]) - 55 elif hnum[hlen]>='a' and hnum[hlen]<='f': rem = ord(hnum[hlen]) - 87 else: chk = 1 break dnum = dnum + (rem * (16 ** i)) hlen = hlen - 1 i = i+1 if chk == 0: print("\nEquivalent Decimal Value = ", dnum) else: print("\nInvalid Input!")
Here is its sample run with hexadecimal input as 23D5:
Hexadecimal to Decimal using int()
This program uses int() method to do the same job. The int() method returns integer (decimal) equivalent of any value passed as its argument.
print("Enter Hexadecimal Number: ", end="") hnum = input() dnum = int(hnum, 16) print("\nEquivalent Decimal Value =", dnum)
Hexadecimal to Decimal using Function
This program is created using user-defined and predefined functions. The user-defined function used here is HexToDec(). This function takes a value (hexadecimal) as its argument and returns its decimal equivalent using int() method:
def HexToDec(h): return int(h, 16) print("Enter Hexadecimal Number: ", end="") hnum = input() dnum = HexToDec(hnum) print("\nEquivalent Decimal Value =", dnum)
Hexadecimal to Decimal using Class
This is the last program of this article, created using a class named CodesCracker. Class is an object-oriented feature of Python language.
class CodesCracker: def HexToDec(self, h): return int(h, 16) print("Enter Hexadecimal Number: ", end="") hnum = input() ob = CodesCracker() dnum = ob.HexToDec(hnum) print("\nEquivalent Decimal Value =", dnum)
Since to access any member function of a class in Python, we must have to create an object of that class. Therefore, an object named ob of class CodesCracker is created. And using this object, we've accessed the member function named HexToDec() using dot (.) operator.
Same Program in Other Languages
- Java Convert Hexadecimal to Decimal
- C Convert Hexadecimal to Decimal
- C++ Convert Hexadecimal to Decimal
« Previous Program Next Program »