from bitarray import bitarray
d=bitarray('0'*30)
d[5]=1

i = 0
for bit in d:
    i = (i << 1) | bit

print i

output: 16777216.

Answer from Serenity on Stack Overflow
Discussions

arrays - Bits list to integer in Python - Stack Overflow
I have such list in Python: [1,0,0,0,0,0,0,0]. Can I convert it to integer like as I've typed 0b10000000 (i.e. convert to 128)? I need also to convert sequences like [1,1,0,0,0,0,0,0,1,0,0,0,0,0,0,... More on stackoverflow.com
🌐 stackoverflow.com
python - Converting a bytearray into an integer - Code Review Stack Exchange
I am working on a program to decode MMS PDU files. They are binary files and I am reading them byte by byte and decoding each header value as I come to it. One header value is the Date, and it's More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
September 30, 2016
python - Integer to bitfield as a list - Stack Overflow
I've created a method to convert an int to a bitfield (in a list) and it works, but I'm sure there is more elegant solution- I've just been staring at it for to long. I'm curious, how would you co... More on stackoverflow.com
🌐 stackoverflow.com
Convert python byte "array" to int "array - Stack Overflow
Releases Keep up-to-date on features we add to Stack Overflow and Stack Internal. ... New: Stack Overflow For Agents. The next generation of knowledge exchange. Learn more · pythonjavascriptc#reactjsjavaandroidhtmlflutterc++node.jstypescriptcssrphpangularnext.jsspring-bootmachine-learning... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert an integer to an array of bits in python
5 Best Ways to Convert an Integer to an Array of Bits in Python - Be on the Right Side of Change
February 18, 2024 - integer = 9 # Convert to binary and remove the '0b' prefix binary_string = bin(integer)[2:] # Use list comprehension to create the bit array bit_array = [int(bit) for bit in binary_string] print(bit_array) ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-binary-list-to-integer
Python - Binary list to integer - GeeksforGeeks
December 30, 2024 - For each binary digit in the list, we use the left shift operator (<<) to shift the bits of number to the left by one place and then use the bitwise OR operator (|) to add the current bit.
🌐
FavTutor
favtutor.com › blogs › binary-string-to-int-python
Convert Binary String to Int in Python (with code)
September 12, 2023 - The character that corresponds ... string into groups of 8 bits, use the int() function alongside the base argument set to 2 (binary) to convert each group into the corresponding integer, and then pass an integer argument ...
Find elsewhere
🌐
Python
wiki.python.org › moin › BitManipulation
BitManipulation - Python Wiki
bitarray - efficient arrays of booleans -- C extension · python-bitstring - A Python module to help you manage your bits. - Google Project Hosting · bitstruct - This module performs conversions between Python values and C bit field structs represented as Python bytearrays. Some simple code is at ActiveState Code Recipes: Bit-field manipulation (in Python 2 syntax). Here are some other examples. To integer.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-convert-bytes-to-int-in-python
How to Convert Bytes to Int in Python? - GeeksforGeeks
July 23, 2025 - Converting bytes to integers in Python involves interpreting a sequence of byte data as a numerical value.
🌐
Quora
quora.com › How-do-I-convert-integers-to-binary-in-Python-3
How to convert integers to binary in Python 3 - Quora
Answer (1 of 7): Use the function ‘bin(x)’ , where x is to be taken as the decimal input and it outputs the binary value as a string: For eg: bin(20) = '0b10100'
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-int-to-bytes-in-python
How to Convert Int to Bytes in Python? - GeeksforGeeks
February 24, 2025 - For example, if the input is b'hello', the output will be 'hello'.This article covers different ways to convert bytes into strings in Pyt ... In Python, you can convert a float to an integer using type conversion.
🌐
AskPython
askpython.com › python › examples › convert-base-2-binary-number-strings-to-integers
Converting Base-2 Binary Number Strings to Integers in Python - AskPython
March 26, 2023 - Ever faced the challenge of converting a binary number string into an integer for smooth processing in your Python code? Python offers seamless solutions for transforming data types without a hitch, making it an ideal choice for developers worldwide. In this article, we’ll delve into two popular methods to tackle binary string conversion: Python’s built-in int() function and the powerful bitstring library, part of the bit array ...
Top answer
1 of 2
106

Python doesn't traditionally have much use for "numbers in big-endian C layout" that are too big for C. (If you're dealing with 2-byte, 4-byte, or 8-byte numbers, then struct.unpack is the answer.)

But enough people got sick of there not being one obvious way to do this that Python 3.2 added a method int.from_bytes that does exactly what you want:

int.from_bytes(b, byteorder='big', signed=False)

Unfortunately, if you're using an older version of Python, you don't have this. So, what options do you have? (Besides the obvious one: update to 3.2, or, better, 3.4…)


First, there's your code. I think binascii.hexlify is a better way to spell it than .encode('hex'), because "encode" has always seemed a little weird for a method on byte strings (as opposed to Unicode strings), and it's in fact been banished in Python 3. But otherwise, it seems pretty readable and obvious to me. And it should be pretty fast—yes, it has to create an intermediate string, but it's doing all the looping and arithmetic in C (at least in CPython), which is generally an order of magnitude or two faster than in Python. Unless your bytearray is so big that allocating the string will itself be costly, I wouldn't worry about performance here.

Alternatively, you could do it in a loop. But that's going to be more verbose and, at least in CPython, a lot slower.

You could try to eliminate the explicit loop for an implicit one, but the obvious function to do that is reduce, which is considered un-Pythonic by part of the community—and of course it's going to require calling a function for each byte.

You could unroll the loop or reduce by breaking it into chunks of 8 bytes and looping over struct.unpack_from, or by just doing a big struct.unpack('Q'*len(b)//8 + 'B' * len(b)%8) and looping over that, but that makes it a lot less readable and probably not that much faster.

You could use NumPy… but if you're going bigger than either 64 or maybe 128 bits, it's going to end up converting everything to Python objects anyway.

So, I think your answer is the best option.


Here are some timings comparing it to the most obvious manual conversion:

import binascii
import functools
import numpy as np

def hexint(b):
    return int(binascii.hexlify(b), 16)

def loop1(b):
    def f(x, y): return (x<<8)|y
    return functools.reduce(f, b, 0)

def loop2(b):
    x = 0
    for c in b:
        x <<= 8
        x |= c
    return x

def numpily(b):
    n = np.array(list(b))
    p = 1 << np.arange(len(b)-1, -1, -1, dtype=object)
    return np.sum(n * p)

In [226]: b = bytearray(range(256))

In [227]: %timeit hexint(b)
1000000 loops, best of 3: 1.8 µs per loop

In [228]: %timeit loop1(b)
10000 loops, best of 3: 57.7 µs per loop

In [229]: %timeit loop2(b)
10000 loops, best of 3: 46.4 µs per loop

In [283]: %timeit numpily(b)
10000 loops, best of 3: 88.5 µs per loop

For comparison in Python 3.4:

In [17]: %timeit hexint(b)
1000000 loops, best of 3: 1.69 µs per loop

In [17]: %timeit int.from_bytes(b, byteorder='big', signed=False)
1000000 loops, best of 3: 1.42 µs per loop

So, your method is still pretty fast…

2 of 2
2

Function struct.unpack(...) does what you need.

🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to convert python bytes to int array
5 Best Ways to Convert Python Bytes to Int Array - Be on the Right Side of Change
February 23, 2024 - The conversion to an int array is then achieved using list comprehension, similar to the previous method. ... With bytearray(byte_data), byte_data is changed into a mutable sequence, after which a list comprehension is used to iterate over it. Since elements of a bytearray are already integers, there’s no need to convert them. The struct module in Python is typically used for packing and unpacking data to and from C-like structures.