Computer >> Computer tutorials >  >> Programming >> Python

Quickly convert Decimal to other bases in Python


In Python, there are some easy methods to convert Decimal numbers to other bases like Binary, Octal & Hexadecimal. For an example, if the number is 19 in Decimal, in binary, it will show 10011, In octal, it will show 23, and in Hexadecimal, it will show 13.

In the result, it will show 0b, 0o, 0x before the numbers of Binary, Octal and Hexadecimal respectively. Using these notations, we can easily determine the base of the number.

Example code

#using bin(), oct(), hex() functions
x = 242
print('The number {} in binary form: {}'.format(x, bin(x)))
print('The number {} in octal form: {}'.format(x, oct(x)))
print('The number {} in hexadecimal form: {}'.format(x, hex(x)))

Output

The number 242 in binary form: 0b11110010
The number 242 in octal form: 0o362
The number 242 in hexadecimal form: 0xf2