1

I just spent ~30 minutes debugging and double checking Python & C# code, to find out that my struct.pack was writing the wrong data. When I separated this into separate calls, it works fine.

This is what I had before

file.write(struct.pack("fffHf", kf_time / frame_divisor, kf_in_tangent, kf_out_tangent, kf_interpolation_type, kf_value))

This is what I have now

file.write(struct.pack("f", kf_time / frame_divisor))
file.write(struct.pack("f", kf_in_tangent))
file.write(struct.pack("f", kf_out_tangent))
file.write(struct.pack("H", kf_interpolation_type))
file.write(struct.pack("f", kf_value))

Why does the first variation not write the data that I expected? What is so different than writing these separately?

(File is opened in binary mode, platform is 64 bit Windows, Python 3.5)

asked May 29, 2017 at 9:28
3
  • can you provide a MCVE? stackoverflow.com/help/mcve Commented May 29, 2017 at 9:30
  • What platform are you on? Is this Python 2 or 3? Did you open the file in binary mode? Commented May 29, 2017 at 9:33
  • 64 bit Windows. Python 3.5. File is opened in Binary mode. Commented May 29, 2017 at 9:34

1 Answer 1

3

Presumably because, as the struct documentation clearly states:

Note By default, the result of packing a given C struct includes pad bytes in order to maintain proper alignment for the C types involved; similarly, alignment is taken into account when unpacking. This behavior is chosen so that the bytes of a packed struct correspond exactly to the layout in memory of the corresponding C struct. To handle platform-independent data formats or omit implicit pad bytes, use standard size and alignment instead of native size and alignment: see Byte Order, Size, and Alignment for details.

answered May 29, 2017 at 9:36
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, that's the reason. You should add a =, < or > at the beginning of the format string, depending on the endianness you want.
Here I was thinking the "</!/>/=" only meant endianness, and had no effect other than that. Thanks!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.