DEV Community

Cover image for Python hex() function, convert decimal to hexadecimal
Python64
Python64

Posted on

11

Python hex() function, convert decimal to hexadecimal

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 (4)

Collapse
 
abbi_jokitsuneabbijkw profile image
Abbi Jo Kitsune (AbbiJKW)

Got me wondering if there were any others apart from 0x and 0b
learned that there's also a rarely used 0o for Octal (base 8) as well as the Hex & Binary notations.

Thought I'd found another until I (finally) discovered 0e4 is just a shorthand for Exponent (Scientific Notation) so will always return Zero, where 2e4 returns float 20,000.0 (2x10x10x10x10), well at least in Python it does. Didn't find any others apart from the three above.

Collapse
 
prernaheera profile image
Prernaheera

why there is ox in front of hexadecimal part

Collapse
 
chinghei1007 profile image
ching hei

Look into the post again

Collapse
 
jarvissilva profile image
Jarvis Silva

Here is the tutorial to convert hex to rgb in python