Home:ALL Converter>How to read float values from binary file using c#?

How to read float values from binary file using c#?

Ask Time:2014-08-07T19:53:11         Author:SanVEE

Json Formatter

I'm trying to read float values from a binary file,

public static void tmpTest ( )
    {
        string fileName = @"c:\debug\tmp_1.bin";

        /* Write */
        using ( BinaryWriter bw = new BinaryWriter ( File.Open( fileName, FileMode.Create ) ))
        {
            bw.Write ( 10.001f );
            bw.Write ( 10.002f );
        }

        /* Read */
        using ( BinaryReader br = new BinaryReader ( File.Open ( fileName, FileMode.Open ) ) )
        {
            int val_1 = br.Read (); // Output : 25
            int val_2 = br.Read (); // Output : 4
        }
    }

I know that I'm missing something at Read section, when I read those values I get val_1 as 25 & val_2 as 4 instead of 10(as the return type is integer), please guide me what am I doing wrong here.

Many Thanks in advance.

Author:SanVEE,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/25181829/how-to-read-float-values-from-binary-file-using-c
DarkWanderer :

Have you checked the documentation? There is a ReadSingle method in BinaryReader for that.\n\nfloat value = binaryReader.ReadSingle();\n",
2014-08-07T11:55:23
Marcos Lora :

You need to read a Single not an Int. If you need an int you can do a cast (int).\n\nMSDN Example\n\nbinaryReader.ReadSingle();\n",
2014-08-07T11:57:19
yy