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?
CodePudding user response:
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
CodePudding user response:
If i am not mis understanding, you want to convert the list of binary to a single decimal int? You can do this.
my_list = [1,0,0,1,0,1,0,1,0,1,0,0,0,1,1,0]
string_ints = [str(i) for i in my_list]
string_ints = ''.join(string_ints)
print(string_ints)
#1001010101000110
num = int(string_ints, 2)
print(num)
#38214