2

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?

1
  • I would use some file format for this: csv, avro, etc. for which both languages have libraries. If it is not possible in your case then you should clarify the question. Commented Dec 18, 2020 at 17:25

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! it worked perfectly and thanks for adding the struct.pack reference! :d
0

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'

Comments

Your Answer

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.