Learnitweb

Base conversion functions in Python

Python provides base conversion functions to convert an integer number to another base. Whenever you print a binary, octal or a hexadecimal integer number, it is printed by default in decimal form. But sometimes there is a need to change base of an integer, for example, decimal form to binary form.

Please note that all binary, octal and hexadecimal representation can not be used for fractional numbers, for example, 1.33.

Following are the base conversion functions:

bin()Convert an integer number to a binary string prefixed with “0b”
oct()Convert an integer number to an octal string prefixed with “0o”
hex()Convert an integer number to a lowercase hexadecimal string prefixed with “0x”

In the following program we’ll convert decimal, binary, octal and hexadecimal integer numbers in other base.

decimalNumber = 123
binaryNumber = 0b101
hexNumber = 0x111
octNumber = 0o111

#convert decimal number to other base
print('Binary representation of decimalNumber is ', bin(decimalNumber))
print('Hexadecimal representation of decimalNumber is ', hex(decimalNumber))
print('Octal representation of decimalNumber is ', oct(decimalNumber))

#to print empty line in console
print()

#convert binary number to other base
print('Decimal representation of binaryNumber is ', int(binaryNumber))
print('Hexadecimal representation of binaryNumber is ', hex(binaryNumber))
print('Octal representation of binaryNumber is ', oct(binaryNumber))

#to print empty line in console
print()

#convert hexadecimal number to other base
print('Decimal representation of hexNumber is ', int(hexNumber))
print('Hexadecimal representation of hexNumber is ', bin(hexNumber))
print('Octal representation of hexNumber is ', oct(hexNumber))

#to print empty line in console
print()

#convert octal number to other base
print('Decimal representation of octNumber is ', int(octNumber))
print('Binary representation of octNumber is ', bin(octNumber))
print('Hexadecimal representation of octNumber is ', hex(octNumber))

Output

Binary representation of decimalNumber is  0b1111011
Hexadecimal representation of decimalNumber is  0x7b
Octal representation of decimalNumber is  0o173

Decimal representation of binaryNumber is  5
Hexadecimal representation of binaryNumber is  0x5
Octal representation of binaryNumber is  0o5

Decimal representation of hexNumber is  273
Hexadecimal representation of hexNumber is  0b100010001
Octal representation of hexNumber is  0o421

Decimal representation of octNumber is  73
Binary representation of octNumber is  0b1001001
Hexadecimal representation of octNumber is  0x49