Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 266
axcelenator Avatar asked Sep 25 '26 20:09

axcelenator


1 Answers

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).

like image 90
bytecode77 Avatar answered Sep 28 '26 09:09

bytecode77



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!