Convert decimal number to binary, octal and hexadecimal using python

This article is going to be a very short one as python directly provides methods to convert a decimal number to binary, octal and hexadecimal numbers.

Convert to binary number

A binary number will have 0 and 1 only. Python provides a method called bin() which takes an integer and convert it into its equivalent binary format.

>> bin(5)
'0b101'
>> bin(1)
'0b1'
>> bin(2)
'0b10'
>> bin(1000)
'0b1111101000'

The result is a string prefixed by ‘0b’.

Convert to an octal number

An octal number will have only digits 0 – 7. Python provides a method called oct() which takes an integer value and convert it into its equivalent octal number.

>> oct(5)
'0o5'
>> oct(9)
'0o11'
>> oct(121)
'0o171'
>> oct(1900)
'0o3554'

The result is a string prefixed by “0o”.

convert to an hexadecimal number

Hexadecimal number uses most often the symbols “0”–”9″ to represent values zero to nine, and “A”–”F” to represent values ten to fifteen. Python provides a method called hex() which takes an integer value and convert it into its equivalent hexadecimal number.

>> hex(12)
'0xc'
>> hex(9)
'0x9'
>> hex(56)
'0x38'
>> hex(569)
'0x239'

Thus we can easily convert decimal number to other formats using python.

decimal to other number formats using python

Happy coding!