Introduction to Number System
In our daily lives, we deal with the base 10 numbers, which are all numbers from 0 to 9.
0,1,2,3,4,5,6,7,8,9
In this number system, all the numbers are made by the combination of these 10 digits.
Python has support for the following number systems also:
- Binary Numbers (or base 2 numbers)
- Octal Numbers (or base 8 numbers)
- Hexadecimal Numbers (or base 16 numbers)
Python Binary Numbers
Binary numbers belong to the base 2 number system. In this, only two digits are used, i.e. 0 and 1. The binary number is prefixed with “0b”.
The bin() function is used to convert any number to a binary number.
Using bin() to convert 100 to binary. It has prefix “0b”.
x = 100
print(bin(x))
If we directly try to print binary number, it will print 100.
print(0b1100100)
If we pass binary number to a variable and try to print it, then it will print binary form.
x = 100
y = bin(x)
print(y)
Python Octal Numbers
Octal numbers belong to the base 8 number system. An octal number can have digit(s) 0,1,2,3,4,5,6,7. The octal number is prefixed with “0o”.
The function oct() is used to convert any number to an octal number.
Using oct() to convert 100 to octal. It has prefix “0o”.
x = 100
print(oct(x))
If we directly try to print octal number, it will print 100.
print(0o144)
If we pass octal number to a variable and try to print it, then it will print octal form.
x = 100
y = oct(x)
print(y)
Python Hexadecimal Numbers
The hexadecimal number belongs to the base 16 number system. Hexadecimal numbers can have 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E. The hexadecimal number is prefixed with “0x”.
The hex() function is used to convert any number to a hexadecimal number.
Using hex() to convert 100 to hexadecimal. It has prefix “0x”.
x = 255
print(hex(x))
If we directly try to print hexadecimal number, it will print 100.
print(0xff)
If we pass hexadecimal number to a variable and try to print it, then it will print hexadecimal form.
x = 100
y = bin(x)
print(y)
References:
- Convert binary, octal, decimal, and hexadecimal in Python
- Convert Decimal to Binary, Octal and Hexadecimal
- Binary, Octal, and Hexadecimal