# Convert decimal to binary, octal, and hexadecimal and vice versa in python

In this article, we shall see how to convert decimal numbers to binary, octal, and hexadecimal using python. We can also see how to convert the binary, octal, and hexadecimal number back to a decimal number. This article is going to be very short as python has built-in methods for every above-mentioned conversion.

The methods that will be used here are,

- bin()
- oct()
- hex()
- int()

Let us get started.

**Convert decimal to binary**

First let us see how to convert decimal to binary using python. This can be done easily using a built-in python method called bin(). This method takes the decimal number and returns the binary string.

Note that by default a ‘0b’ is appended at the beginning indicating a binary number. If we want to convert the binary number back to decimal number we can just use the int() method from python. This method takes two arguments to convert the binary number back to decimal. They are,

- The binary number string
- The base (2 in this case)

**Convert decimal to octal**

Let us now see how to convert the decimal number to octal. This can be done easily using a built-in python method called oct(). This method takes the decimal number and returns the string containing the octal number.

Note that by default a ‘**0o**‘ is appended at the beginning indicating an octal number. If we want to convert the octal number back to decimal number we can just use the **int()** method from python. This method takes two arguments to convert the octal number back to decimal. They are,

- The binary number string
- The base (8 in this case)

**Convert decimal to hexadecimal**

Next, let us see how to convert decimal to hexadecimal and vice versa. This can be done easily using a built-in python method called **hex()**. This method takes the decimal number and returns the string containing the hexadecimal value of the number.

Note that by default a ‘**0x**‘ is appended at the beginning indicating a hexadecimal number. If we want to convert the hexadecimal number back to decimal number we can just use the **int()** method from python. This method takes two arguments to convert the hexadecimal number back to decimal. They are,

- The binary number string
- The base (16 in this case)

**Conclusion**

Hope this article is helpful. Some of us may already know about the bin(), hex() and oct() methods. But using the int() method along with the base to be converted to convert binary, octal and hexadecimal numbers back to the decimal format was new to me. So i wanted to share it with you all.

Happy coding!