How to translate a binary file header sample code (C++/C#) into Python?

2

I am working to write a binary file to save a hardware instruments data (Larson-Davis 831C) based on the manufacturer's sample code. I the following samples:

C++

string create_ldbin_header(int num_files, vector<int>& file_sizes)
{
ostringstream return_value;

int hdr1 = 'LD';
int hdr2 = 'BIN';
int hdr3 = 1;
int hdr4 = num_files;

return_value.write((char*)&hdr1, 4);
return_value.write((char*)&hdr2, 4);
return_value.write((char*)&hdr3, 4);
return_value.write((char*)&hdr4, 4);

for (int i = 0; i < num_files; ++i)
{
    return_value.write((char*)&file_sizes[i], 4);
}
return return_value.str();
}

Another version in C#

private void WriteLDBinHeader(BinaryWriter writer, int fileSize)
        {
            writer.Write();
            writer.Write((Int32)0x0042494E);
            writer.Write((Int32)0x00000001);
            writer.Write((Int32)1);
            writer.Write((Int32)fileSize);
        }

My attempt to do the same in Python has failed. I have tried several versions, and I am not well-versed in struct pack. I think the string represented formatting would be {0:032b}. Anyway, my last attempt was the following:

hdr1 = "LD"
hdr2 = 'BIN'
hdr3 = "1"
hdr4 =str(y[0]["size"])
header = struct.pack('=iiii',hdr1,hdr2,hdr3,hdr4)

with open('instrumentFile.ldbin', 'wb') as f:
    f.write(header + r.content)

Any guidance in the translation would be appreciated.

c#
python
c++
asked on Stack Overflow Dec 30, 2019 by rlinde

2 Answers

0

Try this:

hdr1 = 0x00004c44  # "  LD"
hdr2 = 0x0042494e  # " BIN"
hdr3 = 1
hdr4 = int(y[0]["size"])
header = struct.pack('>iiii',hdr1,hdr2,hdr3,hdr4)

with open('instrumentFile.ldbin', 'wb') as f:
    f.write(header + r.content)
answered on Stack Overflow Dec 30, 2019 by arghol
0

Very helpful.... it didn't work but you gave me the confidence to iterate more. I was able to get a proper working file to compare my download version in the hex dumps, and was able to unwind the problem. So the resulting working code was the following:

hdr1 = 0x00004c44  # "  LD"
hdr2 = 0x0042494e  # " BIN"
hdr3 = 0x00000001  # " Another item buried in documentation but does not match sample C++ code"
hdr4 = 1
hdr5 = 4202629
header = struct.pack('iiiii',hdr1,hdr2,hdr3,hdr4,hdr5)

with open('C:\\WJE Work\\excel\\instrumentFile.ldbin', 'wb') as f:
    f.write(header + r.content)

Interestingly hd3 above was not in the sample C++ code, but it was in the C#.

Appreciate the help!

answered on Stack Overflow Dec 31, 2019 by rlinde

User contributions licensed under CC BY-SA 3.0