【问题标题】:how to take n-bytes from byte string and convert them to one integer如何从字节串中取出n个字节并将它们转换为一个整数
【发布时间】:2023-01-18 00:59:34
【问题描述】:

我有像 b'\x00\x95\xf3\x4c ...' 这样的长字节字符串。我想从这个字符串中读取 n 个字节并将它们转换为一个整数

我试过切片

list_of_int = []
data = b'' #it`s big byte string

while len(data) > 0:
        list_of_int.append(int.from_bytes(data[:4], 'big'))
        data = data[4:]

但是他们太慢了,我怎样才能做得更快?

【问题讨论】:

  • 你能分享一个data的例子吗?

标签: python-3.x


【解决方案1】:

您可以使用struct

import struct

# Building a list of integers
l = [1, 242, 2430, 100, 20]

# Converting it to bytes string
data = bytearray()
for i in l:
    data += i.to_bytes(4, 'little')  # using 'little-endian' representation
print(data)

# Reading bytes string
n = len(l)
list_of_int = struct.unpack("i"*n, data) # reads n integers. Use ">i"*8 for big-endian representation
print(list_of_int)

【讨论】:

  • 我会试试的,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-14
  • 2023-04-01
  • 2023-03-09
  • 2012-09-01
  • 2013-06-08
  • 2014-04-18
  • 1970-01-01
相关资源
最近更新 更多