Explain Codes LogoExplain Codes Logo

Convert base-2 binary number string to int

python
bitwise-operations
binary-conversion
numpy-performance
Alex KataevbyAlex Kataev·Oct 30, 2024
TLDR

To convert a binary string to an integer, Python's int() function paired with 2 as the base easily does the job:

decimal_int = int('1010', 2) # Converts '1010' binary to decimal 10

This enjoyable little one-liner effectively turns binary code, the language of computers, into human-readable numbers. But why stop here? Let's dive deeper.

Elementary conversion methods

The Python way: str-prefix

Python has its own binary literal representation — the prefix '0b'. With this, you can tell Python directly that a string is a binary number:

decimal_int = int('0b1010', 0) # Behold, '0b1010' converts to 10. Amazing, isn't it?

The champ: bitstring

When you need to do more than just convert, the bitstring module is your knight in shining armor with its additional features:

from bitstring import BitArray # Initiate the BitArray with a binary string binary_str = '1010' b_array = BitArray(bin=binary_str) # Convert the binary BitArray to an unsigned int decimal_int = b_array.uint # Converts '1010' to 10 and looks real cool doing it

The big player: numpy

Got a large heap of binary numbers? Fear not, numpy is there to make your conversion efficient and fast:

import numpy as np # Convert an array of binary numbers to integers using numpy binary_array = np.array(['1010', '1111', '0001'], dtype='S4') decimal_array = np.core.defchararray.ljust(binary_array, 32, '0') decimal_ints = np.packbits(decimal_array.view(np.uint8)).view(np.uint32) # See? Didn't break a sweat!

The artisan way: zip and bitwise

Want to convert binary strings the hard way because why not? You have zip and bitwise operations:

binary_str = '1010' # Let's talk numbers, baby decimal_int = sum(val * (2 ** idx) for idx, val in zip(range(len(binary_str)), map(int, reversed(binary_str))))

Bitwise operations and potential errors

While performing conversions, you may need to use bitwise operations and cater to potential errors:

The bitwise playbook

Bitwise operations are the James Bond gadgets of binary manipulation:

# Left shift operation: The Clifford of multiplication by 2 result = 0b1011 << 1 # Results in 0b10110 (or as we humans call it, 22) # Right shift operation: Divide by 2, no more, no less result = 0b1011 >> 1 # Results in 0b101 (or 5, if you prefer simplicity) # Bitwise AND operation: The Sherlock Holmes of masking bits mask = 0b0101 result = 0b1011 & mask # Results in 0b0001 (or if you must know, 1)

An unexpected guest - ValueError

Binary strings can sometimes carry invalid data ('2021'). In such scenarios, Python raises a ValueError:

try: # Who you're gonna call? ValueError busters! decimal_int = int(binary_str, 2) except ValueError: print(f"Error: Invalid binary string {binary_str}. Nothing here but dust and echoes...")

Performance considerations

Lastly, ensure smooth performance. While Python's int() function is your trusty steed for binary-to-integer conversions, numpy is your warhorse when dealing with large binary datasets.