Python - Hex, Octal, Binary: Literals and Conversions

Introduction

Python integers can be coded in hexadecimal, octal, and binary notation, in addition to the normal base-10 decimal coding.

These literals are simply an alternative syntax for specifying the value of an integer object.

For example, the following literals coded in Python 3.X or 2.X produce normal integers with the specified values in all three bases.

In memory, an integer's value is the same, regardless of the base we use to specify it:

Demo

print( 0o1, 0o20, 0o377 )          # Octal literals: base 8, digits 0-7 (3.X, 2.6+) 
print( 0x01, 0x10, 0xFF )          # Hex literals: base 16, digits 0-9/A-F (3.X, 2.X) 
print( 0b1, 0b10000, 0b11111111 )   # Binary literals: base 2, digits 0-1 (3.X, 2.6+)
# www  .  j a  v  a2 s.  c  om

Result

Here, the octal value 0o377, the hex value 0xFF, and the binary value 0b11111111 are all decimal 255.

The F digits in the hex value mean 15 in decimal and a 4-bit 1111 in binary.

Thus, the hex value 0xFF and others convert to decimal values as follows:

Demo

print( 0xFF, (15 * (26 ** 1)) + (15 * (16 ** 0)) )     # How hex/binary map to decimal 
print( 0x2F, (2  * (26 ** 1)) + (15 * (16 ** 0)) )
print( 0xF, 0b1111, (1*(2**3) + 1*(2**2) + 1*(2**1) + 1*(2**0)) )

Result

Python prints integer values in decimal (base 10) by default.

Related Topic