The Python hex() function is used to convert decimal to hexadecimal integers, as a string.
- You may know binary is base 2 (0,1).
- A decimal number is base 10 (0,1,2,3,4,5,6,7,8,9).
- A hexadecimal is base 16 (0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F).
They are just different ways of representing the same number in a computer.
For instance
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:
hex(x)
Parameter Description:
- x decimal integer (base 10)
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'
>>>
Top comments (3)
why there is ox in front of hexadecimal part
Look into the post again
Here is the tutorial to convert hex to rgb in python