Skip to content

[Python] Binary, Octal, Decimal, Hexadecimal And Other Different Base Conversion Methods

Last Updated on 2021-08-24 by Clay

Python is an elegant and easy-to-use programming language, that usually used for AI and data analysis. When we processing scientific computing, we may have some need to convert different bases.

The bases include:

  • Binary
  • Octal
  • Decimal
  • Hexadecimal

These different bases can be converted to each other. The following I record some sample python code to do it, and plot a conversion table.


Convert Between Different Bases

1. Convert decimal to other bases

In Python, we can use bin()oct()hex() functions to convert Decimal to other bases. It should be noted that these functions can only convert INT data type.

Assume we have a value 13 assign to variable decimal.

# coding: utf-8


decimal = 13

print('Binary:', bin(decimal))
print('Octal:', oct(decimal))
print('Hexadecimal:', hex(decimal))



Output:

Binary: 0b1101
Octal: 0o15
Hexadecimal: 0xd

The head of binary will have 0b.
The head of octal will have 0o.
The hexadecimal will have 0x.

It is worth noting that the conversion results are all str data types.


2. Convert other bases to decimal

We can use the int() function to simply convert different bases back to decimal, as in the following example.

# coding: utf-8


decimal = 13


# Convert
binary = bin(decimal)
octal = oct(decimal)
hexadecimal = hex(decimal)


# Print
print('Bin => Dec:', int(binary, 2))
print('Oct => Dec:', int(octal, 8))
print('Hex => Dec:', int(hexadecimal, 16))



Output:

Bin => Dec: 13
Oct => Dec: 13
Hex => Dec: 13

The important thing is that int() is not only the value to be converted (by the way, the input data type is str), but also the value of the conversion base must be input, for example, 2 in binary.


Conversion Table

Untitled Diagram
Tags:

Leave a Reply