Home >Backend Development >Python Tutorial >How to specify hexadecimal and octal integers in Python?

How to specify hexadecimal and octal integers in Python?

王林
王林forward
2023-09-05 09:29:171219browse

How to specify hexadecimal and octal integers in Python?

Hexadecimal and octal are part of the number types in Python. Let's see how to specify them one by one.

For hexadecimal types, add 0x in front. For example -

0x11

For octal types (base 8), add leading 0 (zero). For example -

0O20

Hexadecimal integers in Python

The 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 Represents the numbers from 10. A = 10. B = 11, C = 12, D = 13, E = 14, F = 15. Also known as hexadecimal number system.

Example

To indicate hexadecimal type, add 0x -

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

Output

Hexadecimal = 18
Type = <class 'int'>

Octal integers in Python

Octal numbers use eight digits: 0,1,2,3,4,5,6,7. Also known as the base 8 number system. Each position in an octal number represents base (8) raised to the power 0. The last position in an octal number represents base (8) raised to the x power.

Example

To represent an octal type (base 8), add 0 (zero) in front -

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

Output

Octal = 16
Type = <class 'int'>

Let’s look at other examples -

Convert decimal to octal

Example

To convert decimal to octal, use the oct() method and set the decimal number as the 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 the 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

The above is the detailed content of How to specify hexadecimal and octal integers in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete