Python Binary, Octal and Hexadecimal


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:

  1. Binary Numbers (or base 2 numbers)
  2. Octal Numbers (or base 8 numbers)
  3. 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”.

In [1]:
x = 100
print(bin(x))
0b1100100

If we directly try to print binary number, it will print 100.

In [2]:
print(0b1100100)
100

If we pass binary number to a variable and try to print it, then it will print binary form.

In [3]:
x = 100
y = bin(x)
print(y)
0b1100100

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”.

In [1]:
x = 100
print(oct(x))
0o144

If we directly try to print octal number, it will print 100.

In [2]:
print(0o144)
100

If we pass octal number to a variable and try to print it, then it will print octal form.

In [3]:
x = 100
y = oct(x)
print(y)
0o144

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”.

In [1]:
x = 255
print(hex(x))
0xff

If we directly try to print hexadecimal number, it will print 100.

In [2]:
print(0xff)
255

If we pass hexadecimal number to a variable and try to print it, then it will print hexadecimal form.

In [3]:
x = 100
y = bin(x)
print(y)
0b1100100

References:

  1. Convert binary, octal, decimal, and hexadecimal in Python
  2. Convert Decimal to Binary, Octal and Hexadecimal
  3. Binary, Octal, and Hexadecimal