# Convert Numbers into Binary, Octal, Hexadecimal in Python

## Problem –

You want to convert or output numbers in Binary, Octal and Hexadecimal in python.

## Solution –

To convert a number into Binary, Octal and Hexadecimal, use the bin(), oct() and hex() functions respectively.


In [1]: x = 1000

In [2]: # convert in binary

In [3]: bin(x)
Out[3]: '0b1111101000'

In [4]: # convert in octal

In [5]: oct(x)
Out[5]: '0o1750'

In [6]: # convert in Hexadecimal

In [7]: hex(x)
Out[7]: '0x3e8'

You can also use the format function if you don’t want the 0b, 0o and 0x prefixes.


In [8]: # format in binary

In [9]: format(x, 'b')
Out[9]: '1111101000'

In [10]: # format in octal

In [11]: format(x, 'o')
Out[11]: '1750'

In [12]: # format in hexadecimal

In [13]: format(x, 'x')
Out[13]: '3e8'

If you have negative numbers then the output will also have negative signs.

In [14]: x = -1000

In [15]: format(x, 'b')
Out[15]: '-1111101000'

In [16]: format(x, 'o')
Out[16]: '-1750'

In [17]: format(x , 'x')
Out[17]: '-3e8'

Rating: 1 out of 5.