【问题标题】:convert bytes back to list of integers [duplicate]将字节转换回整数列表[重复]
【发布时间】:2021-12-25 16:33:39
【问题描述】:

我有一个大数字列表:

[123456, 654321]

我正在将每个数字转换为字节:

lst = [(123456).to_bytes(6,'big'), (654321).to_bytes(6,'big')]
>>> [b'\x00\x00\x00\x01\xe2@', b'\x00\x00\x00\t\xfb\xf1']

然后我将此列表转换为字节:

by = b''.join(lst)
>>> b'\x00\x00\x00\x01\xe2@\x00\x00\x00\t\xfb\xf1'

如何从b'\x00\x00\x00\x01\xe2@\x00\x00\x00\t\xfb\xf1' 转换回[123456, 654321]?

【问题讨论】:

标签: python


【解决方案1】:

您可以对字节对象使用切片:

>>> value = b'\x00\x00\x00\x01\xe2@\x00\x00\x00\t\xfb\xf1'

>>> byte1 = value[:6]
>>> print(byte1)
b'\x00\x00\x00\x01\xe2@'

>>> byte2 = value[6:]
>>> print(byte2)
b'\x00\x00\x00\t\xfb\xf1'

然后将字节转换回整数:

>>> num1 =  int.from_bytes(byte1, byteorder='big')
>>> print(num1)
123456

>>> num2 =  int.from_bytes(byte2, byteorder='big')
>>> print(num2)
654321

然后重新添加到列表中:

>>> nums = [num1, num2]
>>> print(nums)
[123456, 654321]

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 2012-05-08
    • 2014-10-17
    • 2019-09-21
    • 2021-07-26
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多