- Python hex() function, convert decimal to hexadecimal
- Syntax
- return value
- examples
- Decimal to Hexadecimal in Python
- Decimal to Hexadecimal Conversion
- Method 1: Using hex() function
- Method 2: Using format() function
- Method 3: Using custom function
- Method 4: Using Recursion
- Conclusion
- Python Program to Convert Decimal to Hexadecimal
- Convert Decimal to Hexadecimal using the hex() method
- Convert Decimal to Hexadecimal using Loop
- Convert Decimal to Hexadecimal using Recursion
- How to convert a decimal value to hexadecimal in Python
Python hex() function, convert decimal to hexadecimal
They are just different ways of representing the same number in a computer.
Hexadecimal | Decimal | Binary |
---|---|---|
A | 10 | 1010 |
B | 11 | 1011 |
C | 12 | 1100 |
10 | 16 | 10000 |
11 | 17 | 10001 |
12 | 18 | 10010 |
Syntax
The syntax of the hex function is:
return value
Returns the hexadecimal number expressed as a string
examples
The following example shows the hex() function in use. It converts the given numbers in decimal into a hexadecimal number:
>>> hex(255) '0xff' >>> hex(-42) '-0x2a' >>> hex(1L) '0x1L' >>> hex(12) '0xc' >>> type(hex (12)) Class 'str'> # String
Compare these with the above table:
>>> hex(3) '0x3' >>> hex(10) '0xa' >>> hex(11) '0xb' >>> hex(12) '0xc' >>>
Computers sometimes put 0x in front, that means the number is a hexadecimal number. For binary it puts 0b in front (try with bin(10) ).
You can also do this for numbers in a list:
>>> numbers = [20,10,40,30,60,50,80,70] >>> for num in numbers: . hex(num) . '0x14' '0xa' '0x28' '0x1e' '0x3c' '0x32' '0x50' '0x46' >>>
Decimal to Hexadecimal in Python
In this guide, you will learn 4 different ways to convert decimal to hexadecimal in Python.
Decimal to Hexadecimal Conversion
Decimal numbers are the numbers that we use generally in our day-to-day life. It includes all the numbers from 0 to 9.
Hexadecimal is a base 16 number system. It uses 16 symbols to represent numbers. The symbols are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
10 is written as A, 11 as B, 12 as C, 13 as D, 14 as E, and 15 as F.
The decimal number can be represented in hexadecimal form:
(0)10 = (0)16 (2)10 = (2)16 (9)10 = (9)16 (10)10 = (A)16 (15)10 = (F)16 (16)10 = (10)16 (25)10 = (19)16 (26)10 = (1A)16 (35)10 = (23)16 (40)10 = (28)16
Steps to convert decimal to hexadecimal:
- Divide the decimal number by 16.
- Get the quotient becomes the new number and the remainder becomes the last digit of the hexadecimal number.
- If the quotient is greater than 9, replace it with the corresponding symbol.
- Repeat the steps until the quotient is 0.
The hexadecimal number system is widely used in computers. It is used to represent color values in HTML and CSS, and to represent memory addresses.
Method 1: Using hex() function
The hex() built-in function converts a number from any base to hexadecimal.
It takes a single argument and returns a string with the hexadecimal representation of the number.
The returned string starts with the 0x prefix.
num = int(input("Enter a number: ")) hex_num = hex(num) print(hex_num) # to remove 0x prefix hex_num = hex_num[2:] print(hex_num)
Enter a number: 25 0x19 19
Method 2: Using format() function
The format() multi-purpose built-in function in Python. It can perform various tasks like formatting strings, numbers, etc.
It takes two arguments: the number to be converted and the base to which it is to be converted.
For example, if the number is 123 and the base is 16, then the format(123, ‘x’) is used.
num = int(input("Enter a number: ")) hex_num = format(num, 'x') print(hex_num)
Enter a number: 40234 9D2A
Method 3: Using custom function
Let’s create your own function using the logic of dividing the number by 16 and getting the remainder.
Steps to convert decimal to hexadecimal:
- Create a function that takes an integer decimal number as an argument.
- Initialize an empty string to store the hexadecimal number.
- Run a while loop until the quotient is greater than 0.
- Get the remainder of the number divided by 16.
- If the remainder is greater than 9, replace it with the corresponding hexadecimal value.
- Append the remainder to the string.
- Finally, reverse the string and return it.
# custom function to convert decimal to hexadecimal def dec2hex(dec): hex = '' while dec > 0: rem = dec % 16 if rem < 10: hex += str(rem) else: hex += chr(rem + 87) dec //= 16 # return reversed string return hex[::-1] num = int(input("Enter a number: ")) print(dec2hex(num))
Enter a number: 28560 6F90
Method 4: Using Recursion
Recursion is a technique of solving a problem where the solution depends on solutions to smaller instances of the same problem.
We can use recursion to convert decimal to hexadecimal.
# recursive function to convert decimal to hexadecimal def dec2hex(dec): if dec == 0: return '' else: rem = dec % 16 if rem < 10: return dec2hex(dec // 16) + str(rem) else: return dec2hex(dec // 16) + chr(rem + 87) num = int(input("Enter a number: ")) print(dec2hex(num))
Conclusion
Now you know 4 different ways by which you can convert decimal to hexadecimal in Python. You can use any of the methods as per your requirement.
Python Program to Convert Decimal to Hexadecimal
Summary: In this programming example, we will learn how to convert a decimal to hexadecimal in Python using hex(), loop, and recursion.
Convert Decimal to Hexadecimal using the hex() method
Python hex() is an inbuilt method that converts an integer to its corresponding hexadecimal form.
hex() returns hexadecimal in the form of string prefixed with 0x .
decimal = int(input("Enter a number: ")) print("Hexadecimal: ",hex(decimal))
Enter a number: 20
Hexadecimal: 0x14
Here the prefix 0x in the output indicates that the number 14 is in hexadecimal form.
Convert Decimal to Hexadecimal using Loop
The standard mathematical way to convert a decimal to hexadecimal is to divide the number by 16 until it reduces to zero.
The sequence of remainders from last to first in hex form is the hexadecimal form of the given decimal number.
The following conversion table is used to convert remainders into hex form:
Here is the implementation of the same in Python using while loop:
conversion_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C', 'D', 'E', 'F'] decimal = int(input("Enter a number: ")) hexadecimal = '' while(decimal>0): remainder = decimal%16 hexadecimal = conversion_table[remainder]+ hexadecimal decimal = decimal//16 print("Hexadecimal: ",hexadecimal)
Enter a number: 44
Hexadecimal: 2C
In this program, inside the while loop, we divide the decimal number until it reduces to zero and simultaneously concatenate the hex form of the remainder to the hexadecimal string using the conversion_table list .
Convert Decimal to Hexadecimal using Recursion
The division method of converting a decimal number to hexadecimal can also be implemented using recursion.
conversion_table = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A' , 'B', 'C', 'D', 'E', 'F'] def decTohex(n): if(n<=0): return '' remainder = n%16 return decTohex(n//16)+conversion_table[remainder] decimal = int(input("Enter a number: ")) print("Hexadecimal: ",decTohex(decimal))
Enter a number: 205
Hexadecimal: CD
After the recursive process, the hex form of the remainder gets concatenated in last to first fashion and is returned to the calling statement.
In this tutorial, we learned multiple ways to convert a decimal number to its corresponding hexadecimal form in Python programming language.
How to convert a decimal value to hexadecimal in Python
In this post, we will learn different ways to convert a decimal value to hexadecimal using Python. Decimal number system is base 10 number system. We can use 0 to 9 to represent a decimal number. Hexadecimal number system is base 16 number system. We have to use 0 to 9 in hexadecimal to represent 0 to 9 decimal values and A to F in hexadecimal for 10 to 15 decimal values.
We can write our own function or we can use an inbuilt function hex to do the decimal to hexadecimal conversion.
Before we write our program, let’s understand the algorithm to do the conversion.
Algorithm to convert a decimal to hexadecimal:
Let’s learn the algorithm to convert a decimal value to hexadecimal:
- Read the decimal value from the user.
- Divide the decimal number by 16.
- Store the remainder in hexadecimal.
- Keep the result and keep dividing the decimal by 16 until you get 0.
- If you combine the remainders in reverse, it will be the hexadecimal conversion.
Example to convert decimal to hexadecimal:
Let me show you an example.
The following table shows the decimal and hexadecimal conversion of the digits:
Now, let’s convert 761 to hexadecimal:
- 761/16, the quotient is 47 and remainder is 9. 9 is 9 in hexadecimal
- 47/16, the quotient is 2 and remainder is 15. 15 is F in hexadecimal
- 2/16, the quotient is 0 and the remainder is 2. 2 is 2 in hexadecimal
If we combine the remainders in reverse, it is 2F9. So, the hexadecimal representation of 761 is 2F9.
Python program 1: Convert decimal to hexadecimal by dividing the number repeatedly:
Let’s write it down in code. This program will take one number as input from the user and it will keep dividing the number by 16 until the quotient becomes 0.
It follows the same steps as we have discussed above.
= 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'> num = int(input('Enter a number: ')) hex = '' while(num > 0): remainder = num % 16 hex = hex_dict[remainder] + hex num = num // 16 print(f'Hexadecimal: hex>')
- hex_dict is a dictionary with decimal keys and hexadecimal values. We will use this dictionary to get the hexadecimal value for the remainders.
- It asks the user to enter a number and stores it in the num variable.
- hex is an empty string variable to hold the hexadecimal string.
- The while loop is finding the hexadecimal value. It keeps running and finds the remainder by dividing the number by 16. It picks the hexadecimal value from the dictionary and appends it to the start of hex.
- Once the loop ends, it prints the hexadecimal value.
If you run this program, it will print output as like below:
Python program 2: Convert decimal to hexadecimal by using a separate method:
Let’s use a separate method to do the conversion.
def decimal_to_hex(num): hex_dict = 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'> hex = '' while(num > 0): remainder = num % 16 hex = hex_dict[remainder] + hex num = num // 16 return hex num = int(input('Enter a number: ')) print(f'Hexadecimal: decimal_to_hex(num)>')
We created a method decimal_to_hex that takes a number as the parameter and returns the hexadecimal value. This is exactly the same program we discussed above. The only difference is that we are using a new method to do the calculation.
It will print a similar result.
Python program 3: Convert decimal to hexadecimal by using a recursive method:
We can use a recursive method to convert a decimal to hexadecimal. Let’s take a look at the program:
= 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'> def decimal_to_hex(num, hex): if num == 0: return hex remainder = num % 16 return decimal_to_hex(num // 16, hex_dict[remainder] + hex) num = int(input('Enter a number: ')) print(f'Hexadecimal: decimal_to_hex(num, "")>')
- decimal_to_hex is a recursive method. It takes a number and one string as the parameter.
- If the value of the number is 0, it will return the string.
- Else, it finds the remainder and calls decimal_to_hex again to find the hexadecimal value. It passes num // 16 as the number and appends the hexadecimal value to the front of the hex string as the second parameter.
If you run this program, it will print a similar result.
Python program 4: Decimal to hexadecimal by using hex:
hex() is a built-in method that can be used to convert an integer to hexadecimal. This method takes an integer as the parameter and returns the hexadecimal value.
Where num is the number parameter. It returns the hexadecimal string. It throws TypeError if anything other than integer values are passed to hex.
= int(input('Enter a number: ')) print(f'Hexadecimal: hex(num)>')
It will give output as like below: