Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Python Code Example: Convert Decimal to Hexadecimal Number

This Python code defines a function called decToHex() that converts a decimal (base-10) number to its hexadecimal (base-16) representation, omitting the ‘0x’ prefix. The function takes an integer x as input, converts it to a hexadecimal string using the hex() function, then splits this string at ‘x’ and returns the last part of the split array, which is the hexadecimal value without the prefix. The print statement calls this function with the argument 140, and prints the hexadecimal representation of 140, which is 8c.

Detailed Breakdown:

  • Function Definition: decToHex(x) converts a decimal number x to a hexadecimal string.
  • Conversion Process: Uses hex(x) to generate the hexadecimal string, then employs split('x') to discard the '0x' prefix.
  • Output: Prints the hexadecimal equivalent of 140 as 8c.

Code Example

def decToHex(x):
    return hex(x).split('x')[-1]

print(decToHex(140))

Output

8c

Code Explanation

The function starts by using the built-in hex function in Python to convert the decimal number x to its equivalent hexadecimal representation. The hexadecimal representation is returned as a string with the prefix 0x attached to it, e.g. 0x8c for the decimal number 140.

Next, the string is split using the split method with the argument 'x'. This will result in a list with two elements: ['0', '8c']. The second element of the list, '8c', is the hexadecimal representation without the 0x prefix. This is obtained using the [-1] list indexing syntax.

Finally, the function returns the hexadecimal representation without the prefix as the output.

When the code is executed, it calls the decToHex function with the argument 140. This will result in the hexadecimal representation of 140, '8c', being printed to the console.