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

How to specify hexadecimal and octal integers in Python?

王林
Release: 2023-09-05 09:29:17
forward
1218 people have browsed it

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
Copy after login

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

0O20
Copy after login

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))
Copy after login

Output

Hexadecimal = 18
Type = <class 'int'>
Copy after login

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))
Copy after login

Output

Octal = 16
Type = <class 'int'>
Copy after login

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)))
Copy after login

Output

Decimal = 110
The number 110 in octal form = 0o156
Copy after login

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)))
Copy after login

Output

Decimal =  110
The number 110 in hexadecimal form = 0x6e
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template