P. Johansson
P. Johansson

Reputation: 1

struct.pack_into requires more bytes then specified in format

Python struct.pack_into with format char 'x' requires more bytes.

I am trying to learn about python byte arrays to be able to write my own IP,TPC,UDP headers. I use the struct in python to pack and unpack binary data so the specified types given the format string.

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

print(struct.unpack(">bx", ba2))

Now when I try to pack into a buffer of length 2 with ">bx" as format, according to above code, I get the error:

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

but I have a byte array of 2 bytes.

What am I doing wrong?

And please reference to some documentation, if I have missed it (I have read the python doc, but may have missed it).

Edit:

Sorry if I was unclear. but i want to just change the second byte in the byte array. Thus the 'x' padd in the format.

And as stupid as i was it is just to exclude the 'x' in the format like thiss:

struct.pack_into(">b", ba2, 1, 1)

and the right packing will have ben made. With this output:

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

Upvotes: 0

Views: 4778

Answers (2)

P. Johansson
P. Johansson

Reputation: 1

And as stupid as i was it is just to exclude the 'x' in the format like thiss:

struct.pack_into(">b", ba2, 1, 1)

and the right packing will have ben made. With this output:

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

Upvotes: 0

aldarel
aldarel

Reputation: 456

You need one additional parameter for pack_into() function call. The third parameter is mandatory and it is offset in the target buffer (refer to https://docs.python.org/2/library/struct.html). Your format is also incorrect, because it just expects one byte. Following code fixes your problems:

import struct

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

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

Upvotes: 1

Related Questions