Reading Time: 1 minutes
Number System Interconversion in Python
Python provides handy builtin functions bin(), hex() & oct() to convert decimal values to strings of corresponding number systems.
>>> a = 4 >>> bin(a) '0b100' >>> hex(a) '0x4' >>> oct(a) '0o4'
To convert these strings back into decimal system, use the builtin int() function with appropriate base value.
>>> int('0b100', 2) 4 >>> int('0x4', 16) 4 >>> int('0o4', 8) 4
You can use the combination of these methods to convert one non-decimal system to another. For example, converting a binary value to its hexadecimal equivalent:
>>> hex( int('0b100', 2) ) '0x4'