简体   繁体   English

将列表中的序列化位连接成字节

[英]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]我有一个 python 列表,其中的数据以序列化形式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.我想将这个 16 位序列化数据连接到一个 int 中。 The 16 bits are stored from MSB to LSB, MSB in index 0 16 位从 MSB 存储到 LSB,MSB 在索引 0 中

I tried doing bitwise operations with a for loop我尝试使用 for 循环进行按位运算

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?或者这无关紧要并且错误不是来自将它们连接为整数而是来自其他东西?

You missed the index by one.你错过了一个索引。 The for loop only iterates through values of i from 0 to 14 inclusive. for 循环仅遍历从 0 到14i值(包括 0 到 14)。 To get it to loop through all 16 values, you need to set the endpoint to 16.要让它遍历所有 16 个值,您需要将端点设置为 16。

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

This will output 0x9546 , as expected.正如预期的那样,这将输出0x9546

There's also a preferred way of writing this (or use enumerate if you also need the index):还有一种首选的编写方式(如果您还需要索引,请使用enumerate ):

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM