struct.pack_into需要更多的字节,然后以格式指定 Python struct.pack_为char'x'格式需要更多字节。

struct.pack_into需要更多的字节,然后以格式指定 Python struct.pack_为char'x'格式需要更多字节。,python,arrays,struct,format,Python,Arrays,Struct,Format,我试图学习python字节数组,以便能够编写自己的IP、TPC和UDP头。我使用python中的struct来打包和解包二进制数据,这样指定的类型就得到了格式字符串 ba2 = bytearray(2) print(ba2, "The size: ", ba2.__len__()) struct.pack_into(">bx", ba2, 1, 1) print(struct.unpack(">bx", ba2)) 现在,当我尝试将“>bx”作为格式打包到长度为2的缓冲区中时,根

我试图学习python字节数组,以便能够编写自己的IP、TPC和UDP头。我使用python中的struct来打包和解包二进制数据,这样指定的类型就得到了格式字符串

ba2 = bytearray(2)
print(ba2, "The size: ", ba2.__len__())
struct.pack_into(">bx", ba2, 1, 1)

print(struct.unpack(">bx", ba2))
现在,当我尝试将
“>bx”
作为格式打包到长度为2的缓冲区中时,根据上面的代码,我得到了错误:

bytearray(b'\x00\x00') The size:  2
Traceback (most recent call last):
  File "D:/User/Documents/Python/Network/Main.py", line 58, in <module>
    bitoperations_bytes_bytearrays_test()
  File "D:/User/Documents/Python/Network/Main.py", line 49, in bitoperations_bytes_bytearrays_test
    struct.pack_into(">bx", ba2, 1, 1)
struct.error: pack_into requires a buffer of at least 2 bytes
本会做好正确的包装。使用此输出:

bytearray(b'\x00\x00') The size:  2
A pack with one byte shift:  0001
(0, 1)
bytearray(b'\x00\x00') The size:  2
A pack with one byte shift:  0001
(0, 1)

对于pack_into()函数调用,还需要一个额外的参数。第三个参数是必需的,它是目标缓冲区中的偏移量(请参阅)。您的格式也不正确,因为它只需要一个字节。以下代码修复了您的问题:

import struct

ba2 = bytearray(2)
print(ba2, "The size: ", ba2.__len__())
struct.pack_into("bb", ba2, 0, 1, 1)

print(struct.unpack("bb", ba2))

和我一样愚蠢的是,只是以这样的格式排除了“x”:

struct.pack_into(">b", ba2, 1, 1)
struct.pack_into(">b", ba2, 1, 1)
本会做好正确的包装。使用此输出:

bytearray(b'\x00\x00') The size:  2
A pack with one byte shift:  0001
(0, 1)
bytearray(b'\x00\x00') The size:  2
A pack with one byte shift:  0001
(0, 1)

谢谢你的回答。但是我希望能够在第一个字节的左边只添加一个字节(00000001),而不改变它,因此pad字节x。因为如果我只想在标题中添加一个字段,我需要从开头开始做一个偏移(在本例中为1),而不是用一些东西填充第一个空格。