Number Conversion

Numbers are the fundamental building blocks of programming. Whether you’re displaying scores in a game, calculating values in a finance app, or manipulating raw data, understanding how to convert numbers between different formats is vital. In Python, number conversion allows you to switch between the familiar decimal system and other bases like binary, octal, and hexadecimal. These conversions are not only academically interesting but essential for working with low-level data, debugging, and understanding how computers represent information.

In this lesson, we’ll explore how to convert numbers between various bases using Python. You’ll learn how to:

  • Convert decimal numbers to binary, octal, and hexadecimal formats.
  • Convert strings representing numbers in other bases back to integers.
  • Understand the built-in Python functions that simplify number conversion.

By the end of this lesson, you’ll be confident in handling number conversions in your programs, empowering you to work effectively with different numeric representations.

The Basics: Number Systems You Should Know

Before diving into Python code, let’s quickly recap the common number systems:

  • Decimal (Base 10): The number system we use daily, digits 0-9.
  • Binary (Base 2): Uses only digits 0 and 1. Computers use binary internally.
  • Octal (Base 8): Uses digits 0-7. Less common, but sometimes used in computing.
  • Hexadecimal (Base 16): Uses digits 0-9 and letters A-F (or a-f). Common in programming for compact binary representation.

💡 Why Different Number Bases?

While humans prefer decimal, computers operate in binary. Hexadecimal and octal are shorthand ways to represent binary data more compactly and understandably. For example, one hex digit corresponds to four binary digits, making it easier to read large binary numbers.

Converting Decimal to Other Number Systems

Python provides simple built-in functions to convert decimal integers to binary, octal, and hexadecimal strings.

  • bin(): Converts an integer to a binary string prefixed with 0b.
  • oct(): Converts an integer to an octal string prefixed with 0o.
  • hex(): Converts an integer to a hexadecimal string prefixed with 0x.

📌 Deep Dive: Decimal to Binary, Octal, Hexadecimal

PYTHON
number = 255

binary_repr = bin(number)
octal_repr = oct(number)
hex_repr = hex(number)

print(f"Decimal: {number}")
print(f"Binary: {binary_repr}")   # Output: 0b11111111
print(f"Octal: {octal_repr}")     # Output: 0o377
print(f"Hexadecimal: {hex_repr}") # Output: 0xff
Output
Decimal: 255 Binary: 0b11111111 Octal: 0o377 Hexadecimal: 0xff

Notice that the output strings include prefixes (0b, 0o, 0x) that indicate the base. This is useful when reading output, but sometimes you may want just the digits, which we’ll cover shortly.

Converting Strings in Other Bases Back to Integers

Often you receive numbers as strings representing binary, octal, or hexadecimal values. To perform calculations, you need to convert them back into integers. Python’s int() function is very flexible and can accept a second argument specifying the base of the input string.

📌 Deep Dive: String to Integer Conversion

PYTHON
binary_str = "11111111"
octal_str = "377"
hex_str = "ff"

# Convert back to decimal integers
decimal_from_bin = int(binary_str, 2)
decimal_from_oct = int(octal_str, 8)
decimal_from_hex = int(hex_str, 16)

print(f"Binary '{binary_str}' to decimal: {decimal_from_bin}")
print(f"Octal '{octal_str}' to decimal: {decimal_from_oct}")
print(f"Hex '{hex_str}' to decimal: {decimal_from_hex}")
Output
Binary '11111111' to decimal: 255 Octal '377' to decimal: 255 Hex 'ff' to decimal: 255

The int() function’s base parameter accepts values between 2 and 36, allowing conversions from many number systems.

💡 Handy Tip

If your input string includes the base prefix (like 0b for binary), you can omit the base argument or set it to zero, and Python will infer the base automatically:

int('0xff', 0)  # returns 255

Removing Prefixes When Converting Back to Strings

Sometimes, you want to convert numbers to binary, octal, or hex without the prefixes (0b, 0o, 0x). This is especially useful for formatting output or embedding numbers in strings.

Python strings have formatting options to remove those prefixes:

  • Use string slicing to remove first two characters (the prefix).
  • Or use the format() function with format specifiers 'b', 'o', and 'x'.

📌 Deep Dive: Format Numbers Without Prefixes

PYTHON
number = 255

# Using slicing to remove prefixes
binary_str = bin(number)[2:]
octal_str = oct(number)[2:]
hex_str = hex(number)[2:]

print(f"Binary without prefix: {binary_str}")
print(f"Octal without prefix: {octal_str}")
print(f"Hex without prefix: {hex_str}")

# Using format()
binary_fmt = format(number, 'b')
octal_fmt = format(number, 'o')
hex_fmt = format(number, 'x')

print(f"Binary (format): {binary_fmt}")
print(f"Octal (format): {octal_fmt}")
print(f"Hex (format): {hex_fmt}")
Output
Binary without prefix: 11111111 Octal without prefix: 377 Hex without prefix: ff Binary (format): 11111111 Octal (format): 377 Hex (format): ff

Using format() is often preferred because it is clearer and avoids potential errors if the prefix length changes in the future.

Working With Uppercase Hexadecimal

By default, hexadecimal digits from format() and hex() are lowercase. Sometimes you might want uppercase letters (A-F). You can achieve this easily:

  • Use the format specifier 'X' instead of 'x'.
  • Or use the string method .upper() on the output.

📌 Deep Dive: Uppercase Hexadecimal

PYTHON
number = 255

hex_upper_1 = format(number, 'X')
hex_upper_2 = hex(number)[2:].upper()

print(f"Uppercase hex (format): {hex_upper_1}")
print(f"Uppercase hex (upper method): {hex_upper_2}")
Output
Uppercase hex (format): FF Uppercase hex (upper method): FF

Summary of Python Number Conversion Functions

Number Conversion Functions in Python
Function/MethodPurpose
bin(int)Convert integer to binary string with 0b prefix
oct(int)Convert integer to octal string with 0o prefix
hex(int)Convert integer to hexadecimal string with 0x prefix
int(str, base)Convert string in specified base (2-36) to integer
format(int, 'b')Format integer as binary string without prefix
format(int, 'o')Format integer as octal string without prefix
format(int, 'x')Format integer as lowercase hex string without prefix
format(int, 'X')Format integer as uppercase hex string without prefix
Architecture of Number Conversion
Architecture of Number Conversion

Practical Example: Parsing User Input in Different Bases

Imagine you are building a calculator that accepts numbers in various formats. You want to allow the user to enter binary, octal, decimal, or hexadecimal numbers, and then convert them all to a decimal integer for calculation.

Here’s a simple approach:

📌 Deep Dive: User Input Number Conversion

PYTHON
def parse_number(user_input):
    user_input = user_input.strip().lower()
    
    if user_input.startswith('0b'):
        return int(user_input, 2)
    elif user_input.startswith('0o'):
        return int(user_input, 8)
    elif user_input.startswith('0x'):
        return int(user_input, 16)
    else:
        # Assume decimal if no prefix
        return int(user_input, 10)

# Examples:
print(parse_number("0b1010"))  # binary 10 decimal
print(parse_number("0o12"))    # octal 10 decimal
print(parse_number("10"))      # decimal 10 decimal
print(parse_number("0xA"))     # hex 10 decimal
Output
10 10 10 10

This function lets your program be flexible and user-friendly by accepting multiple numeric formats.

⚠️ Watch Out for Invalid Input

When converting strings to integers, invalid inputs will raise a ValueError. Always validate or handle exceptions when working with user input.

Advanced: Using int() with Base 0

Python’s int() function can automatically detect the base if you pass 0 as the second argument. This means you can parse strings with prefixes without specifying the exact base manually.

📌 Deep Dive: Auto-Detect Base with int()

PYTHON
print(int("0b1010", 0))  # 10 decimal
print(int("0o12", 0))    # 10 decimal
print(int("10", 0))      # 10 decimal (no prefix, decimal)
print(int("0xA", 0))     # 10 decimal
Output
10 10 10 10

This can simplify your parsing logic significantly.

Summary and Best Practices

Number conversion in Python is straightforward thanks to built-in functions and flexible parsing options. Here are some best practices to keep in mind:

  • Use bin(), oct(), and hex() for quick conversions from integers to strings with prefixes.
  • Use format() for cleaner strings without prefixes or for formatting output.
  • Use int(string, base) to convert strings in any base back to integers.
  • Use base 0 in int() to auto-detect the base from prefixes when parsing mixed input.
  • Always validate or handle exceptions when converting user input to avoid runtime errors.

Mastering these techniques will empower you to handle a wide variety of programming challenges involving numbers.