A decimal is a term that describes the base- number system; for example,
A hexadecimal is a term that describes the base- number system.
The digits used in hexadecimal are , followed by , where represents the decimal number , represents , and so on up to representing .
There are two ways in which we can convert decimal to hexadecimal numbers:
hex()
functionStep 1: Start by entering the decimal number provided.
Step 2: Divide the decimal value by .
Step 3: Convert the remainder obtained in Step 2 to the equivalent hexadecimal digit. If the remaining is less than , the remainder should be used as the hexadecimal digit. Use the matching letter instead, where represents , represents , and so on.
Step 4: Add the hexadecimal digit received to the front of the result.
Step 5: Steps 2–4 must be repeated until the decimal number reaches zero.
Step 6: The hexadecimal representation of the original decimal number is obtained as a result.
Example: Convert the decimal number into hexadecimal.
hex()
functionWe can convert a decimal number to hexadecimal in Python using the built-in hex()
function. It takes a parameter decimal number and returns its hexadecimal number.
Here is the syntax for using the hex()
function:
hex(decimal_number)
The following code shows the conversion from decimal to hexadecimal using both methods:
# Method 1 (Using the manual steps)def decimal_to_hexadecimal(decimal_num):hex_characters = "0123456789ABCDEF"if decimal_num == 0:return "0"hexadecimal = ""while decimal_num > 0:remainder = decimal_num % 16hexadecimal = hex_characters[remainder] + hexadecimaldecimal_num //= 16return hexadecimaldecimal_number = 1000hexadecimal_value = decimal_to_hexadecimal(decimal_number)print("Manual steps output: ", hexadecimal_value)# Method 2 (Using the hex function)decimal_number = 1000hexadecimal_value = hex(decimal_number)print("Hex function output: ", hexadecimal_value)
hex_characters
is a string containing the hexadecimal digits. It’s used to map the remainder to the corresponding hexadecimal digit.decimal_num
is 0
, it directly returns “0” since the hexadecimal representation of 0
is “0”.while
loop, the decimal number is continuously divided by 16, and the remainder is used to index into the hex_characters
string to get the corresponding hexadecimal digit. This digit is then concatenated to the left side of the hexadecimal
string. After obtaining the hexadecimal digits in reverse order, the function returns the final hexadecimal value.decimal_number
variable with the value 1000
.decimal_to_hexadecimal
function is called with decimal_number
as an argument, and the resulting hexadecimal value is stored in the hexadecimal_value
variable. The hexadecimal value is printed along with a label using the print
function.hex
function is called with decimal_number
as an argument. This function converts the decimal number to a string representing its hexadecimal value, with the 0x
prefix.Free Resources