Home >Backend Development >Python Tutorial >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
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.
To indicate hexadecimal type, add 0x -
in fronta = 0x12 print("Hexadecimal = ",a) print("Type = ",type(a))
Hexadecimal = 18 Type = <class 'int'>
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.
To represent an octal type (base 8), add 0 (zero) in front -
a = 0O20 print("Octal = ",a) print("Type = ",type(a))
Octal = 16 Type = <class 'int'>
Let’s look at other examples -
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)))
Decimal = 110 The number 110 in octal form = 0o156
To convert decimal to hexadecimal, use the hex() method and set the decimal number as the parameter -
# 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)))
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!