Search code examples
pythonbitwise-operators

Concatenate serialized bits from list into bytes


I have a python list with data in serialized form my_list = [1,0,0,1,0,1,0,1,0,1,0,0,0,1,1,0]

I want to concatenate this 16 bit serialized data into a single int. The 16 bits are stored from MSB to LSB, MSB in index 0

I tried doing bitwise operations with a for loop

tmp = 0;
for i in range(0,15)
    tmp = tmp << 1 | my_list[i]

my_int = hex(tmp)

print(my_int)
     

However when I go to print, it displays the incorrect value in hex. Can I perform these bitwise concatenations with the items in the list as ints or do I need to convert them to another data type. Or does this not matter and the error is not coming from concatenating them as ints but from something else?


Solution

  • You missed the index by one. The for loop only iterates through values of i from 0 to 14 inclusive. To get it to loop through all 16 values, you need to set the endpoint to 16.

    for i in range(16):
        tmp = (tmp << 1) | my_list[i]
    

    This will output 0x9546, as expected.

    There's also a preferred way of writing this (or use enumerate if you also need the index):

    for bit in my_list:
        tmp = (tmp << 1) | bit