0

input:

    print(struct.pack("b", 0)
    print(struct.pack("b", 0))
    print(struct.pack("I", 3))
    print(struct.pack("I", 0))
    print(struct.pack("I", 0))
    print((struct.pack('bbIII', 0, 0, 3, 0, 0)))

output:

   b'\x00'
   b'\x00'
   b'\x03\x00\x00\x00'
   b'\x00\x00\x00\x00'
   b'\x00\x00\x00\x00'
   b'\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

Singed chars at the last row are returning 2bytes for some reason.I don't understand why the last bytearray is returning the longer value than what I expect, I would like to know a reason and a solution of it. Thanks.

1 Answer 1

1

The struct is using the default @ character to represent native size and alignment. This is what's causing the sizes to be different. See the docs.

You can instead use = which will use native byte order but standard size.

print(struct.pack("=b", 0))
print(struct.pack("=bbIII", 0, 0, 3, 0, 0))
b'\x00'
b'\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' #14 bytes instead of 16
Sign up to request clarification or add additional context in comments.

1 Comment

So in other words, the extra bytes are padding to meet some arbitrary alignment requirement. Nice catch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.