axcelenator
axcelenator

Reputation: 1527

Write float array into a binary file c#

I have a float array :

float[] samples32array

I need to convert it into a binary file so I can read it in matlab.

Is there any way to do that?

Upvotes: 3

Views: 8378

Answers (3)

bytecode77
bytecode77

Reputation: 14860

It's simple. First, you should use FileStream and create a file. Then, you can use BinaryWriter, which can write any C# datatype into an underlaying stream, such as a FileStream.

using (FileStream file = File.Create(path))
{
    using (BinaryWriter writer = new BinaryWriter(file))
    {
        foreach (float value in samples32array)
        {
            writer.Write(value);
        }
    }
}

Since the constructor of BinaryWriter accepts the basic type Stream, any stream type can be used. It works for file streams as well as NetworkStream or a MemoryStream etc. It's a very generic class.

And please avoid converting the float[] into a byte[] beforehand as it will allocate memory and this is bad if your array is big (don't know if that's the case for you).

Upvotes: 5

jwatts1980
jwatts1980

Reputation: 7356

This SO answer shows a way to convert a float array into a byte array. Then you can use File.WriteAllBytes() method to write it out to a file. How MatLab reads it, though, will be the issue.

I found some documentation for MatLab for the fread command. It looks like is has some arguments that will allow you to define the precision of the read. You may be able to use "float" as the precision value. Though, the is a bit of an educated guess as I am not very familiar with MatLab.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503090

You can use BinaryWriter to write the data to a file very easily:

foreach (var value in samples32array)
{
    writer.Write(value);
}

Now BinaryWriter is guaranteed to use little-endian format, so in your Matlab call, you should specify a machinefmt value of l to explicitly read it in little-endian format too.

Upvotes: 3

Related Questions