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?
1 Answer 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:
(Tested; this code works with Python 2.7 as well as 3.6.)