To convert a number from base 10 to base 16 in Python, we can use the built-in hex()
function.
The hex()
function takes an integer as its argument and returns a string representing the hexadecimal value of that integer. Here's an example:
main.py45 chars5 lines
Output:
main.py5 chars2 lines
In the example above, we first define a variable num
and set it to the decimal value 255
. We then call the hex()
function with num
as its argument and assign the resulting hexadecimal value to a new variable hex_num
. Finally, we print out the value of hex_num
.
Note that the hex()
function returns a string, so if you need to perform any arithmetic operations on the resulting value, you will need to convert it back to an integer using the int()
function:
main.py68 chars5 lines
Output:
main.py4 chars2 lines
In the example above, we first define a variable hex_num
and set it to the string value '0xff'
. We then call the int()
function with hex_num
as its first argument and 16
as its second argument to specify that the input string is in base 16. We assign the resulting integer value to a new variable decimal_num
and print out its value.
gistlibby LogSnag