﻿ How to Convert a Decimal Number Into Binary, Octal, or Hexadecimal in Python ﻿ # How to Convert a Decimal Number Into Binary, Octal, or Hexadecimal in Python In this article, we show how to convert a decimal number into a binary, octal, or hexadecimal value in Python.

Being able to convert number into other number formats can be useful for a variety of tasks. When working with microcontrollers, for example, numbers can be fed into it using binary or hexadecimal.

Python has built-in functions that allow us to convert decimal numbers into other number formats, including binary, octal, or hexadecimal number formats.

bin() allows us to convert a decimal number to binary.

oct() allows us to convert a decimal number to octal.

hex() allows us to convert a decimal number to hexadecimal.

This is shown in the following code below.

So the decimal number we have is 1004.

We us the bin(), oct(), and hex() functions to convert them into binary, octal, and hexadecimal number formats, respectively.

Notice that binary numbers begin with 0b, octal numbers begin with 0o, and hexadecimal numbers begin with 0x.

If you were using a computer programming language such as C to program embedded systems, you would see this convention as well.

However, if you don't want these prefixes to appear before the number, you can use the format() function to remove them.

This is shown in the code below.

You can see with the format() function, we were able to remove the prefixes from the various number formats.

If you were wanted to act in reverse and convert a number from another number format into decimal, you can use the int() function to do this.

You would specify the number as the first parameter of the int() function and the number system as the second parameter.

This is shown below.

Thus, you can see that we can use the int() function to convert a number from a different number format to decimal.

So this is how to convert a decimal number into a binary, octal, or a hexadecimal number in Python.

Related Resources

How to Randomly Select From or Shuffle a List in Python