Open In App

Convert Bytes To Bits in Python

Last Updated : 12 May, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Converting bytes to bits in Python involves representing each byte in its binary form, where each byte is composed of 8 bits. For example , a byte like 0xAB (which is 171 in decimal) would be represented as '10101011' in binary. Let’s explore a few techniques to convert bytes to bits in Python.

Using int.from_bytes(...).bit_length()

This method converts a byte sequence to an integer using int.from_bytes() and then calculates the number of bits required to represent that integer using .bit_length().

Python
a = b'\x01\x23\x45\x67\x89\xAB\xCD\xEF'

b = int.from_bytes(a, byteorder='big').bit_length()
print(b) 

Output
57

Explanation: int.from_bytes(a, byteorder='big').bit_length() converts a byte sequence a to an integer (big-endian) and returns the number of bits needed to represent that integer.

Using generator expression

This method counts the number of 1 bits in each byte of the byte sequence by converting each byte to its binary form and counting the occurrences of 1 using a generator expression and bin(byte).count('1').

Python
a = b'\x01\x23\x45\x67\x89\xAB\xCD\xEF'
b = sum(bin(byte).count('1') for byte in a)
print(b) 

Output
32

Explanation: sum(bin(byte).count('1') for byte in a) converts each byte in a to binary, counts the number of 1 bits and sums them up.

Using bitwise shift

This approach constructs the integer by shifting each byte into its correct position using bitwise left shift (<<) and OR (|). After constructing the full integer, it calculates the bit length using .bit_length().

Python
a = b'\x01\x23\x45\x67\x89\xAB\xCD\xEF'
val = 0

for byte in a:
    val = (val << 8) | byte
b = val.bit_length()
print(b)

Output
57

Explanation: for byte in a: val = (val << 8) | byte constructs an integer val by shifting it left by 8 bits for each byte and OR'ing the byte. After all bytes are processed, val.bit_length() returns the number of bits needed to represent val.

Using binary string join

This method creates a binary string by converting each byte to its 8-bit binary representation and joining them. Then, it calculates the bit length by measuring the length of the binary string after stripping leading zeros.

Python
a = b'\x01\x23\x45\x67\x89\xAB\xCD\xEF'
binary_str = ''.join(f"{byte:08b}" for byte in a)
b = len(binary_str.lstrip('0'))
print(b)

Output
57

Explanation: ''.join(f"{byte:08b}" for byte in a) converts each byte in a to its 8-bit binary form and concatenates them into one string. binary_str.lstrip('0') removes leading zeros and len(binary_str) calculates the number of remaining bits.



Similar Reads