0

I have a Perl script that creates a binary input file that we pass to another set of code. The binary input file consists of hundreds of parameters that are of various lengths. Most are either 8, 16, or 32 bits. I'm trying to convert the Perl script over to Python, and what is tripping me up are the few parameters that are 24 bits long.

I looked at this forum post, it was close, but not quite what I need.

For example. Lets say the input value is an integer (10187013). How do I pack that down to 3 bytes? If I do something like this:

 hexVars = struct.pack("<L", 10187013)

And then write it out to the binary file:

 binout = open(binFile, "wb")
 binout.write(hexVars)

It, as expected, prints out four bytes 05 71 9b 00, what I want is 05 71 9b. Can I force it to pack only 3 bytes? Or somehow remove the last byte before writing it out?

asked Oct 25, 2018 at 19:51

1 Answer 1

1

Packing into an L always gives you 4 bytes -- because that is the meaning of L. Use 3 separate variables (each one 1 byte), or, since you are converting to a string anyway, just lop off the fourth, unused, byte:

import struct
hexVars = struct.pack("<L", 10187013)[:3]
print (len(hexVars))
print (ord(hexVars[0]),ord(hexVars[1]),ord(hexVars[2]))
binout = open('binFile', "wb")
binout.write(hexVars)

Contents of binFile is as expected:

enter image description here

(Tested; this code works with Python 2.7 as well as 3.6.)

answered Oct 25, 2018 at 20:54
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I knew the "<L" was going to give me the 4 bytes, what I couldn't figure out was how to rid myself of the unwanted 4th byte. The [:3] did the trick.

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.