## Understanding Number Systems

In Python, there are four commonly used number systems: **binary**, **octal**, **decimal**, and **hexadecimal**. Each system represents numbers using a different base or radix.

**Binary** (base 2) uses only two digits, 0 and 1, to represent numbers. For example, the binary representation of the decimal number 5 is `101`

.**Octal** (base 8) uses digits from 0 to 7. The octal representation of the decimal number 9 is `11`

.**Decimal** (base 10) is the most familiar one and uses digits from 0 to 9. For example, the decimal number 23 is represented as `23`

.**Hexadecimal** (base 16) uses digits from 0 to 9 and letters from A to F. The hexadecimal representation of the decimal number 27 is `1B`

.

While working with Python, you might need to convert between these number systems. Thankfully, Python provides built-in functions like `bin()`

, `oct()`

, and `hex()`

to make these conversions straightforward.

To convert a decimal number to binary, octal, or hexadecimal, use the following code:

decimal_number = 345 binary_number = bin(decimal_number) octal_number = oct(decimal_number) hexadecimal_number = hex(decimal_number) print("The decimal number", decimal_number, "is:") print(binary_number, "in binary.") print(octal_number, "in octal.") print(hexadecimal_number, "in hexadecimal.")

This code would output:

The decimal number 345 is: 0b101011001 in binary. 0o531 in octal. 0x159 in hexadecimal.

## Python Built-In Functions for Conversion

Python offers a variety of built-in functions that allow you to convert numbers among different bases such as binary, octal, decimal, and hexadecimal formats. In this section, we will discuss the following functions: `bin()`

, `hex()`

, `oct()`

, and `int()`

.

The `bin()`

function is used to convert a given integer into its binary representation. The output is a string, where the first two characters are `'0b'`

, followed by the binary digits.

For example:

binary_number = bin(10) print(binary_number) # Output: '0b1010'

Similarly, the `oct()`

function returns the octal representation of an integer, with the first two characters being `'0o'`

.

An example usage is as follows:

octal_number = oct(64) print(octal_number) # Output: '0o100'

For converting an integer into its hexadecimal representation, the `hex()`

function is used. The output string starts with `'0x'`

.

Here is an example:

hexadecimal_number = hex(255) print(hexadecimal_number) # Output: '0xff'

Finally, the `int()`

function can also be employed for conversion purposes. Not only does it convert a float to a string, but it can also convert a number in a different base (like binary or hexadecimal) to its decimal equivalent by specifying the base as the second argument.

For instance:

decimal_number = int('1010', 2) # Binary to decimal print(decimal_number) # Output: 10 decimal_number = int('0xff', 16) # Hexadecimal to decimal print(decimal_number) # Output: 255

In summary, the built-in functions `bin()`

, `oct()`

, `hex()`

, and `int()`

enable you to carry out number conversion tasks in Python to create binary, octal, hexadecimal, and integer numbers.

## Converting Decimal to Binary, Octal, and Hexadecimal

In Python, converting decimal numbers to binary, octal, and hexadecimal is quite simple.

π‘ **Info**: Decimal numbers are used in our everyday life and have a base of 10, which means numbers 0 through 9 are used to represent a number. Binary numbers, on the other hand, have a base of 2 (0 and 1), octal numbers have a base of 8 (0-7), and hexadecimal numbers have a base of 16 (0-9 and A-F).

To convert a decimal number to binary, we can use the built-in `bin()`

function, which takes an integer as input and returns a binary string.

For example:

decimal_number = 10 binary_number = bin(decimal_number) print(binary_number)

For converting a decimal number to octal, we can use the `oct()`

function:

decimal_number = 10 octal_number = oct(decimal_number) print(octal_number)

Similarly, to convert a decimal number to hexadecimal, we use the `hex()`

function:

decimal_number = 10 hexadecimal_number = hex(decimal_number) print(hexadecimal_number)

It’s essential to note that the conversion functions `bin()`

, `oct()`

, and `hex()`

all return a string that starts with a prefix indicating the base – `'0b'`

for binary, `'0o'`

for octal, and `'0x'`

for hexadecimal.

If you want to remove the prefix and display the number only, you can use slice notation:

binary_number = bin(decimal_number)[2:] octal_number = oct(decimal_number)[2:] hexadecimal_number = hex(decimal_number)[2:]

You can watch my explainer video on slicing right here:

## Converting Binary, Octal, and Hexadecimal to Decimal

When converting the binary, octal, decimal, and hexadecimal number systems, it’s crucial to understand their bases β binary (base 2), octal (base 8), decimal (base 10), and hexadecimal (base 16).

To convert a binary, octal, or hexadecimal number to its decimal representation in Python, you can use built-in functions like `int()`

.

Let’s explore this process for each number system:

**Binary to Decimal** – To convert a binary string to decimal, you can pass the binary string and its base (`2`

for binary) as arguments to the `int()`

function:

binary_string = "1010" decimal_number = int(binary_string, 2) print(decimal_number) # Output: 10

**Octal to Decimal** – Converting an octal number to decimal is similar to the binary conversion. Pass the octal string and its base (`8`

for octal) as arguments to the `int()`

function:

octal_string = "12" decimal_number = int(octal_string, 8) print(decimal_number) # Output: 10

**Hexadecimal to Decimal** – To convert a hexadecimal number to decimal, use the `int()`

function with the hexadecimal string and its base (`16`

for hexadecimal) as arguments:

hex_string = "A" decimal_number = int(hex_string, 16) print(decimal_number) # Output: 10

In case you need to convert a hexadecimal string to an integer, you can follow this tutorial, which provides a step-by-step guide on achieving this task in Python.

Additionally, when working with HEX values and trying to convert them to their ASCII string representation in Python, you might find this article helpful.

## Custom Conversion Functions

In Python, you can create custom functions to handle conversions between different number systems such as binary, octal, decimal, and hexadecimal. These functions can provide a flexible approach to converting custom input values.

One way to create a custom conversion function is by using a function that takes an `integer`

as an input and returns its binary, octal, or hexadecimal representation as a string. When converting values, you’ll likely encounter both `characters`

and `digits`

.

Consider the following example:

def int_to_binary(num): return bin(num)[2:] def int_to_octal(num): return oct(num)[2:] def int_to_hex(num): return hex(num)[2:]

These custom functions take an integer and utilize Python’s built-in functions to convert the given number into binary, octal, or hexadecimal representations. The `[2:]`

slice is necessary to remove the prefix (e.g., `"0b"`

for binary or `"0o"`

for octal).

To convert a list of integers to their corresponding equivalent in another number base, you can use Python’s list comprehension technique. For instance, converting a list of integers to a string list of binary values can be accomplished with the `[int_to_binary(x) for x in integers]`

expression.

Further, to convert between different types of lists, such as converting a list of strings to a list of integers or floats, you can use the list comprehensions outlined in these articles: String List to Integer List and String List to Float List.

Another useful conversion function is converting a decimal value to a specific base with the digits represented as characters.

This can be done using the function below:

def int_to_base(num, base): value_map = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" if num == 0: return '0' digits = [] while num: digits.append(value_map[num % base]) num //= base return ''.join(digits[::-1])

This function allows conversion of the decimal `integer`

`num`

to any specified `base`

, with the base’s `digits`

represented as characters in the output string.

## Advanced Conversion Techniques

When dealing with strings, particularly for hexadecimal conversion, you can use the `bytes.fromhex()`

method. It parses a hexadecimal string and converts it into a bytes object.

For more advanced cases, you can use the `format()`

function, which provides a diverse range of options for converting and representing numbers. The `format()`

function accepts a variable and a format specifier, which determines how the variable should be formatted.

The syntax is:

formatted_variable = format(variable, format_specifier)

For example, to convert an integer into its binary, octal, and hexadecimal representation using `format()`

:

decimal_num = 12 binary_num = format(decimal_num, 'b') octal_num = format(decimal_num, 'o') hexadecimal_num = format(decimal_num, 'x') print(binary_num) # Output: 1100 print(octal_num) # Output: 14 print(hexadecimal_num) # Output: c

Conversion tables can be useful when dealing with a large number of numbers or when working with bits, characters, and other concepts. Using a conversion table, you would match corresponding values from one number system to another, allowing for an organized and efficient conversion process.

## Using Python Libraries for Conversion

Python provides various libraries for handling conversions between binary, octal, decimal, and hexadecimal number systems. Among these libraries, **NumPy**, **Pandas**, and **Scikit-learn** are popular choices for data manipulation and scientific computing.

π’ **NumPy** is a powerful library for numerical operations in Python. It is particularly suited for working with multi-dimensional arrays and matrices. You can easily convert between different number systems using built-in functions such as `binary_repr`

, `base_repr`

, and `fromiter`

.

Here’s a code example using NumPy:

import numpy as np decimal_number = 42 binary_number = np.binary_repr(decimal_number) hexadecimal_number = np.base_repr(decimal_number, base=16) octal_number = np.base_repr(decimal_number, base=8) print(f'Decimal: {decimal_number}, Binary: {binary_number}, Octal: {octal_number}, Hexadecimal: {hexadecimal_number}') # Output: Decimal: 42, Binary: 101010, Octal: 52, Hexadecimal: 2A

πΌ **Pandas** is a popular library for data manipulation and analysis, including converting numbers between base systems. While Pandas doesn’t have dedicated functions for the conversions, it can easily handle the conversions using the `apply`

method along with the built-in Python functions.

Here’s an example using Pandas:

import pandas as pd data = {'Decimal': [10, 15, 25, 30]} df = pd.DataFrame(data) df['Binary'] = df['Decimal'].apply(bin) df['Octal'] = df['Decimal'].apply(oct) df['Hexadecimal'] = df['Decimal'].apply(hex) print(df)

Output:

```
Decimal Binary Octal Hexadecimal
0 10 0b1010 0o12 0xa
1 15 0b1111 0o17 0xf
2 25 0b11001 0o31 0x19
3 30 0b11110 0o36 0x1e
```

π€ **Scikit-learn** is a powerful machine learning library in Python, widely used for data mining and data analysis. While it may not be directly involved in binary, octal, decimal, and hexadecimal conversions, it is worth mentioning due to its extensive use in the scientific community and compatibility with NumPy and Pandas.

## Frequently Asked Questions

### How can I convert binary to decimal in Python?

To convert binary to decimal in Python, you can use the `int()`

function with the base argument set to 2. For example, to convert the binary number ‘1010’ to decimal:

binary_number = '1010' decimal_number = int(binary_number, 2) print(decimal_number) # Output: 10

This method converts the binary string to a decimal integer.

### What is the method to convert decimal to octal in Python?

You can convert a decimal number to octal using the `oct()`

function. The function takes a decimal integer as input and returns a string representing the octal value. Here’s an example:

decimal_number = 16 octal_number = oct(decimal_number) print(octal_number) # Output: '0o20'

The output string includes the ‘0o’ prefix, which represents an octal number in Python.

### How do I convert hexadecimal to binary in Python?

To convert a hexadecimal number to binary in Python, first convert the hexadecimal to decimal using `int()`

with base 16, then convert the decimal to binary using `bin()`

. For example:

hex_number = '1A' decimal_number = int(hex_number, 16) binary_number = bin(decimal_number) print(binary_number) # Output: '0b11010'

This method converts the hexadecimal string to a binary string, including the ‘0b’ prefix.

### What is the process for converting decimal to hexadecimal in Python?

To convert a decimal number to hexadecimal in Python, use the `hex()`

function. The function takes a decimal integer as input and returns a string representing the hexadecimal value. Here’s an example:

decimal_number = 42 hexadecimal_number = hex(decimal_number) print(hexadecimal_number) # Output: '0x2a'

The output string includes the ‘0x’ prefix, which represents a hexadecimal number in Python.

### How can I convert octal to binary in Python?

To convert an octal number to binary in Python, first convert the octal to decimal using `int()`

with base 8, then convert the decimal to binary using `bin()`

. For example:

octal_number = '72' decimal_number = int(octal_number, 8) binary_number = bin(decimal_number) print(binary_number) # Output: '0b111010'

This method converts the octal string to a binary string, including the ‘0b’ prefix.

### What is the best way to convert binary to octal in Python?

To convert a binary number to octal in Python, first convert the binary to decimal using `int()`

with base 2, then convert the decimal to octal using `oct()`

. For example:

binary_number = '101101' decimal_number = int(binary_number, 2) octal_number = oct(decimal_number) print(octal_number) # Output: '0o55'

This method converts the binary string to an octal string, including the ‘0o’ prefix.

π **Recommended**: Python OpenAI API Cheat Sheet (Free)

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.