How do I specify hexadecimal and octal integers in Python?


The Hexadecimal and Octal are part of Numeric Types in Python. Let’s see how to specify them one by one.

For hexadecimal type, add a preceding 0x. For example −

0x11

For Octal type (base 8), add a preceding 0 (zero). For example −

0O20

Hexadecimal Integers in Python

Hexadecimal Number System uses 10 digits and 6 letters, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F Letters represent the numbers starting from 10. A = 10. B = 11, C = 12, D = 13, E = 14, F = 15 Also called as base 16 number system.

Example

To represent hexadecimal type, add a preceding 0x −

a = 0x12 print("Hexadecimal = ",a) print("Type = ",type(a))

Output

Hexadecimal = 18
Type = <class 'int'>

Octal Integers in Python

Octal Number uses eight digits, 0,1,2,3,4,5,6,7. Also called as base 8 number system. Each position in an octal number represents a 0 power of the base (8). Last position in an octal number represents a x power of the base (8).

Example

To represent Octal type (base 8), add a preceding 0 (zero) −

a = 0O20 print("Octal = ",a) print("Type = ",type(a))

Output

Octal = 16
Type = <class 'int'>

Let us see other examples −

Convert Decimal to Octal

Example

To convert Decimal to Octal, use the oct() method and set the Decimal Number as a parameter −

# Decimal Number dec = 110 # Display the Decimal Number print("Decimal = ",dec) # Display the Octal form print('The number {} in octal form = {}'.format(dec, oct(dec)))

Output

Decimal = 110
The number 110 in octal form = 0o156

Convert Decimal to Hexadecimal

To convert Decimal to Hexadecimal, use the hex() method and set the Decimal Number as a parameter −

Example

# Decimal Number dec = 110 # Display the Decimal Number print("Decimal = ",dec) # Display the Hexadecimal form print('The number {} in hexadecimal form = {}'.format(dec, hex(dec)))

Output

Decimal =  110
The number 110 in hexadecimal form = 0x6e

Updated on: 16-Sep-2022

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements