Python - Convert integers to and from other bases' digit strings

Introduction

You can use built-in functions to convert integers to other bases' digit strings:

Demo

print( oct(64), hex(64), bin(64) )               # Numbers=>digit strings

Result

The oct function converts decimal to octal, hex to hexadecimal, and bin to binary.

int function converts a string of digits to an integer.

Its an optional second argument specifies the numeric base:

Demo

print( 64, 0o100, 0x40, 0b1000000 )             # Digits=>numbers in scripts and strings 
print( int('64'), int('100', 8), int('40', 16), int('1000000', 2) )
print( int('0x40', 16), int('0b1000000', 2) )    # Literal forms supported too
# from   w  w w .  ja  v  a2 s. co m

Result

The eval function treats strings as though they were Python code.

Demo

print( eval('64'), eval('0o100'), eval('0x40'), eval('0b1000000') )

Result

You can convert integers to base-specific strings with string formatting method calls and expressions, which return just digits, not Python literal strings:

Demo

print( '{0:o}, {1:x}, {2:b}'.format(64, 64, 64) )     # Numbers=>digits, 2.6+ 
print( '%o, %x, %x, %X' % (64, 64, 255, 255) )        # Similar, in all Pythons 
# from   ww  w.  j  ava  2 s  .  c o m
X = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF 
print( X )
print( oct(X) )
print( bin(X) )

Result

Related Topic