A Guide to Integer Data Types in Python - Part 2

A Guide to Integer Data Types in Python - Part 2

Examining the Key Concepts of Python's Integer Data Types

In Python, integers serve as objects and belong to the int class. The int class, which is a component of Python's standard library, offers numerous methods for generating integer objects. These methods essentially function as constructors, enabling the creation of int objects from a variety of data types or representations. The following are some prevalent techniques for constructing integer objects:

  1. Direct Assignment: You can create an integer object by directly assigning a whole number to a variable:
x = 42
  1. Using the int() Constructor: The int() constructor can be used to create an integer from various data types. For example:
>>> a = int(10)
>>> print(a)
10
>>> b = int(-10)
>>> print(b)
-10
>>> c = int(10.9)
>>> print(c)
10
>>> d = int(-10.9)
>>> print(d)
-10
>>> e = int(True)
>>> print(e)
1
>>> f = int("10")
>>> print(f)
10
  1. Using Base Notations: You can create integers in different base notations, such as binary, octal, or hexadecimal:
binary_num = int("1010", 2)  # Creates an integer from a binary string (binary_num will be 10)
octal_num = int("16", 8)     # Creates an integer from an octal string (octal_num will be 14)
hex_num = int("1A", 16)      # Creates an integer from a hexadecimal string (hex_num will be 26)
💡
If the base is not specified, the default is base - 10
  1. Reverse Process: Changing an integer from base 10 to another base
>>> bin(10)
'0b1010'
>>> oct(10)
'0o12'
>>> hex(10)
'0xa'

These prefixes are consistent with integer using a based prefix ( no strings attached)

Base Change Algorithm

To convert a number from one base to another base in Python, you can implement a base change algorithm. Here's a simple Python function that converts a number from one base to another:

def base_change(number, from_base, to_base):
    # Convert the number to decimal (base 10)
    decimal_number = 0
    power = 0

    while number > 0:
        digit = number % 10
        decimal_number += digit * (from_base ** power)
        number //= 10
        power += 1

    # Convert the decimal number to the target base
    result = ""
    while decimal_number > 0:
        remainder = decimal_number % to_base
        result = str(remainder) + result
        decimal_number //= to_base

    return result

# Example usage:
number_to_convert = 1010
from_base = 2
to_base = 10

result = base_change(number_to_convert, from_base, to_base)
print(result)  # Output: '10'

This base_change function first converts the input number from the source base to decimal (base 10) by repeatedly multiplying the digits by appropriate powers of the source base. Then, it converts the decimal number to the target base by repeatedly taking remainders when divided by the target base.

You can use this function to convert numbers between different bases by specifying the from_base and to_base as arguments.

In many cases, when working with bases higher than 10, it's common to use the digits 0-9 for values 0 to 9 and then letters A-Z (or a-z) for values 10 to 35 (or 36 in the case of lowercase letters). This is a convention for representing digits in bases greater than 10, known as "base36" or "base62," depending on the set of characters used.

Base16, also known as hexadecimal, is a widely used encoding scheme that represents each digit with 16 possible characters: 0-9 and A-F (or a-f). Here's how you can implement a base16 (hexadecimal) encoding and decoding algorithm in Python:

def encode_base16(number):
    if not isinstance(number, int) or number < 0:
        raise ValueError("Input must be a non-negative integer.")

    hex_chars = "0123456789ABCDEF"
    result = ""

    while number > 0:
        number, remainder = divmod(number, 16)
        result = hex_chars[remainder] + result

    return result

def decode_base16(encoded_str):
    hex_chars = "0123456789ABCDEF"
    hex_dict = {char: index for index, char in enumerate(hex_chars)}

    encoded_str = encoded_str.upper()  # Ensure input is in uppercase
    decoded_number = 0

    for char in encoded_str:
        if char not in hex_chars:
            raise ValueError(f"Invalid character in input: {char}")
        decoded_number = decoded_number * 16 + hex_dict[char]

    return decoded_number

# Example usage:
original_number = 48879
encoded_str = encode_base16(original_number)
print(encoded_str)  # Output: 'BEEF'

decoded_number = decode_base16(encoded_str)
print(decoded_number)  # Output: 48879

In this example, we use the character '0123456789ABCDEF' (uppercase) to represent values from 0 to 15 in base16. The encode_base16 function converts an integer to a base16 string, and the decode_base16 function converts a base16 string back to an integer. We also ensure that the input is in uppercase for consistency.

You can use these functions to encode and decode hexadecimal values in your Python programs.

Here's an example of how you can implement a base36 encoding and decoding algorithm in Python:

import string

def encode_base36(number):
    if not isinstance(number, int) or number < 0:
        raise ValueError("Input must be a non-negative integer.")

    base36_chars = string.digits + string.ascii_uppercase
    result = ""

    while number > 0:
        number, remainder = divmod(number, 36)
        result = base36_chars[remainder] + result

    return result

def decode_base36(encoded_str):
    base36_chars = string.digits + string.ascii_uppercase
    base36_dict = {char: index for index, char in enumerate(base36_chars)}

    decoded_number = 0
    for char in encoded_str:
        decoded_number = decoded_number * 36 + base36_dict[char]

    return decoded_number

# Example usage:
original_number = 1234567890
encoded_str = encode_base36(original_number)
print(encoded_str)  # Output: 'KF12OI'

decoded_number = decode_base36(encoded_str)
print(decoded_number)  # Output: 1234567890

In this example, we use the digits 0-9 and uppercase letters A-Z to represent values from 0 to 35 in base36. You can extend this concept to other bases by adjusting the set of characters used and the corresponding values assigned to them.

This article explains how to create and manipulate integer objects in Python using various techniques, such as direct assignment, the int() constructor, and base notations. It also covers the implementation of base change algorithms to convert numbers between different bases, including examples for base16 (hexadecimal) and base36 encoding and decoding.

Did you find this article valuable?

Support TechWhisperer by becoming a sponsor. Any amount is appreciated!