Reading a python binary file with a C# BinaryReader

Viewed 451

I need to export some data like integers, floats etc. to a binary file with python. Afterwards, I have to read the file with C# again but it doesnt work for me.

I tried several ways of writing a binary file with python and it works as long as I read it with python as well:

a = 3
b = 5

with open('test.tcd', 'wb') as file:
    file.write(bytes(a))
    file.write(bytes(b))

or writing it like this:

import pickle as p

with open('test.tcd', 'wb') as file:
    p.dump([a, b], file)

Currently I am reading the file in C# like this:

static void LoadFile(String path)
{
       BinaryReader br = new BinaryReader(new FileStream(path, FileMode.Open));
       int a = br.ReadInt32();
       int b = br.ReadInt32();

       System.Diagnostics.Debug.WriteLine(a);
       System.Diagnostics.Debug.WriteLine(b);

       br.Close();
}

Unfortunately the output isnt 3 and 5, instead my output is just zero. How do i read or write the binary file properly?

2 Answers

In Python, you have to write your integers with 4 bytes each. Read more here: struct.pack

a = 3
b = 5

with open('test.tcd', 'wb') as file:
     f.write(struct.pack("<i", 3))
     f.write(struct.pack("<i", 5))

Your C# code should work now.

It's possible python is not writing data in the same format that C# expects. You may need to swap byte endianess or do something else. You could read the raw bytes instead and use BitConverter to see if that fixes it.

Another option is to specify the endianess explicitly in python, I think big endian is the default binary reader format for C#.

an_int = 5


a_bytes_big = an_int.to_bytes(2, 'big')

print(a_bytes_big)

Output

b'\x00\x05'


a_bytes_little = an_int.to_bytes(2, 'little')

print(a_bytes_little)

Output

b'\x05\x00'
Related