Binary Conversion and Bitwise Operations (OR, XOR) in Python

Learn how to convert integers to binary and perform bitwise OR and XOR operations in Python using built-in operators and custom implementations.

Python provides built-in functions and operators for converting between integers and binary string representations, as well as for performing bitwise logical operations. This article introduces their basic usage and custom function implementations.

Binary Conversion

Using Python’s built-in bin() function, you can convert an integer to a binary string with a “0b” prefix.

num = 10
binary_str = bin(num)
print(f"Binary representation of {num}: {binary_str}") # Output: Binary representation of 10: 0b1010

Preparing Binary Representations with a Custom Function

To perform bitwise logical operations, we implement a function that converts two numbers into binary lists of equal length, padding the shorter one with zeros.

def prepare_binary_lists(num1, num2):
    # Convert to binary string using bin() and remove '0b' prefix
    bin_str1 = bin(num1)[2:]
    bin_str2 = bin(num2)[2:]

    # Pad the shorter one with zeros to equalize lengths
    max_len = max(len(bin_str1), len(bin_str2))
    bin_list1 = [int(bit) for bit in bin_str1.zfill(max_len)]
    bin_list2 = [int(bit) for bit in bin_str2.zfill(max_len)]

    return bin_list1, bin_list2

# Example
b1, b2 = prepare_binary_lists(3, 5)
print(f"Binary list of 3: {b1}") # Output: Binary list of 3: [0, 1, 1]
print(f"Binary list of 5: {b2}") # Output: Binary list of 5: [1, 0, 1]

Decimal Conversion

A function to convert a binary list back to a decimal number.

def binary_list_to_decimal(binary_list):
    decimal_num = 0
    power = 0
    # Process the binary list from right to left
    for bit in reversed(binary_list):
        if bit == 1:
            decimal_num += (2 ** power)
        power += 1
    return decimal_num

# Example
print(f"Convert [1, 0, 1] to decimal: {binary_list_to_decimal([1, 0, 1])}") # Output: Convert [1, 0, 1] to decimal: 5

Bitwise OR Operation

Python has a built-in bitwise OR operator |.

result_or = 3 | 5
print(f"3 (0b011) OR 5 (0b101) = {result_or} (0b{bin(result_or)[2:]})") # Output: 3 (0b011) OR 5 (0b101) = 7 (0b111)

Custom OR Operation

def custom_or(num1, num2):
    bin_list1, bin_list2 = prepare_binary_lists(num1, num2)
    or_result_list = []
    for i in range(len(bin_list1)):
        if bin_list1[i] == 1 or bin_list2[i] == 1:
            or_result_list.append(1)
        else:
            or_result_list.append(0)
    return binary_list_to_decimal(or_result_list)

# Example
print(f"Custom OR function: 3 OR 5 = {custom_or(3, 5)}") # Output: Custom OR function: 3 OR 5 = 7

Bitwise XOR Operation

Python has a built-in bitwise XOR operator ^.

result_xor = 3 ^ 5
print(f"3 (0b011) XOR 5 (0b101) = {result_xor} (0b{bin(result_xor)[2:]})") # Output: 3 (0b011) XOR 5 (0b101) = 6 (0b110)

Custom XOR Operation

def custom_xor(num1, num2):
    bin_list1, bin_list2 = prepare_binary_lists(num1, num2)
    xor_result_list = []
    for i in range(len(bin_list1)):
        if bin_list1[i] != bin_list2[i]: # When bits differ
            xor_result_list.append(1)
        else:
            xor_result_list.append(0)
    return binary_list_to_decimal(xor_result_list)

# Example
print(f"Custom XOR function: 3 XOR 5 = {custom_xor(3, 5)}") # Output: Custom XOR function: 3 XOR 5 = 6

Summary

In Python, the built-in operators | (OR) and ^ (XOR) are the most efficient and recommended way to perform bitwise logical operations. Custom functions are useful for learning purposes to understand how these operations work.