How To Convert Bytes To Bits In Python With Examples

Hello everyone, welcome to this video. In this session, I will share three methods to convert bytes to bits. First, we will use bitwise operations to extract bits from each byte. Then, we will use string formatting to represent bytes as 8-bit binary strings. Lastly, we will explain how to use the Bitarray library to process and convert byte data. If you want to learn how to efficiently convert bytes to bits, don’t miss this video.

1. Video.

2. Python Source Code.

'''
Get source code from URL: https://www.dev2qa.com/how-to-convert-bytes-to-bits-in-python-with-examples/

How to convert bytes to bits, but first you need to understand that one byte is composed of 8 bits.

for example for binary character b'h': it's decimal unicode code point is 104, and in binary system it is 01101000 which equals to 64(2**6) + 32(2**5) + 8(2**3) = 104 in decimal system.

so that what we want to show you is that how to get the binary value (01101000) of the binary string b'h'.

'''

'''
1. **Bitwise Operations**:
'''
def use_bitwise_operations(byte_sequence):  # Define a function that takes a sequence of bytes as input
    bits = []  # Initialize an empty list to store bits
    for byte in byte_sequence:  # Iterate over each byte in the input sequence
        print('byte:', byte)  # Print the current byte for debugging purposes
        
        # For each byte, we extract its bits
        for i in range(8):  # Iterate 8 times, once for each bit in the byte
            # Shift the byte to the right by the appropriate number of positions (7 to 0) 
            # and use the bitwise AND operation with 1 to extract each bit.
            bits.append((byte >> (7 - i)) & 1)  # Append the extracted bit to the bits list
    return bits  # Return the list of bits


'''
2. **String Formatting**:
'''
def use_string_formatting(byte_sequence):  # Define a function that takes a sequence of bytes as input
 
    bit_strings = []  # Initialize an empty list to store the binary string representations of each byte

    for byte in byte_sequence:  # Iterate over each byte in the input sequence
        bit_string = f'{byte:08b}'  # Format the byte as an 8-bit binary number and store it as a string
        bit_strings.append(bit_string)  # Append the binary string to the list

    bits = ''.join(bit_strings)  # Join all the binary strings together into a single string

    return bits  # Return the string of bits


'''
3. **`bitarray` Library**:
'''
from bitarray import bitarray  # Import the bitarray class from the bitarray library

def use_the_bitarray_library(byte_sequence):  # Define a function that takes a sequence of bytes as input
    
    bits = bitarray()  # Initialize an empty bitarray object
    bits.frombytes(byte_sequence)  # Populate the bitarray with bits from the byte sequence
    return bits.tolist()  # Convert the bitarray to a list of bits and return it




if __name__ == "__main__":

    # Example usage
    #byte_sequence = b'h'
    byte_sequence = b'hello'
    #bits = use_bitwise_operations(byte_sequence)
    bits = use_string_formatting(byte_sequence)
    #bits = use_the_bitarray_library(byte_sequence)
    print(bits)

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.