如何将字节转换回元组列表?

How to convert bytes back to list of tuples?

我想从字节转换回我拥有的元组列表。

lst 是元组 (x,y) 的列表,x 和 y 是整数。

转字节的代码为:

b = b''.join([(x << 16 | (y & 2 ** 16 - 1)).to_bytes(6, 'big') for x, y in lst])

现在我想编写函数来获取 b 变量并将其转换回该列表。
我该怎么做?

while(b!=b''):
   Z=b[:6]
   Q=Z[4:]
   A=int.from_bytes(Q,'big')
   w=int.from_bytes(z,'big')
   w=w>>16
   lst.append((w,A))
   b=b[6:]

例如列表 ([(1, 1), (2, 2)], [(1, 1), (2, 1)], [(2, 1)], [(1 , 2), (2, 1)]) 转换为字节。

我编写的将字节转换回列表的代码,我得到了列表:

([(1, 1), (1, 2)], [(1, 1), (1, 1)], [(1, 1)], [(1, 2), ( 1, 1)])

# Encode
x_encoded = bytes([t[0] for t in lst])
y_encoded = bytes([t[1] for t in lst])
# Decode
x_decoded = [v for v in x_encoded]
y_decoded = [v for v in y_encoded]

result = list(zip(x_decoded, y_decoded))

只需使用索引访问编码数据即可将它们转换回整数。

参考资料:

您不能对任意 整数值做您想做的事情,因为它们在转换为字节流的过程中会丢失信息。但是,对于 x 到 4,294,967,295 和 y 到 65535 的无符号值,以下将起作用:

def grouper(n, iterable):
    "s -> (s0, s1, ...sn-1), (sn, sn+1, ...s2n-1), (s2n, s2n+1, ...s3n-1), ..."
    return zip(*[iter(iterable)]*n)

lst = [(0,65_535), (2,3), (4,5), (4_294_967_295, 42)]
bytes_ = b''.join([(x << 16 | (y & 2 ** 16 - 1)).to_bytes(6, 'big') for x, y in lst])
ints = (int.from_bytes(group, 'big') for group in grouper(6, bytes_))
tuples = [((v & 0xffffffff0000) >> 16, v & 0x00000000ffff) for v in ints]
print(tuples)  # -> [(0, 65535), (2, 3), (4, 5), (4294967295, 42)]