gpt4 book ai didi

python - 在 python 中处理字节

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:34 26 4
gpt4 key购买 nike

我必须获取字节数组并将其发送到套接字。

结构看起来像:1 字节 + 2 字节 + 2 字节。

第一个字节是数字“5”,第二个 2 个字节应该从变量 first 中获取,第三个 2 个字节应该从变量 second 中获取。在 Python 中执行此操作的正确方法是什么?

id = 5      # Fill as 1 byte
first = 42 # Fill as 2 bytes
second = 58 # The same as first

最佳答案

使用 struct module :

>>> import struct
>>> id, first, second = 5, 42, 58
>>> struct.pack('>bhb', id, first, second)
b'\x05\x00*:'

您可能想弄清楚您的数据是 a) little endian 还是 b) signed 或 unsigned;上面的示例使用大端排序和有符号值。

结果(在 python 3 中)是一个 bytes 对象。

关于python - 在 python 中处理字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12073115/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com