11

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.

2
  • 1
    You have to use the appropriate Read method when reading the number back out ReadSingle() for Float, ReadDouble() for Double, etc. MSDN BinaryReader Methods Commented Aug 7, 2014 at 11:59
  • why am I down voted?? could you please put your comments before you down vote something. Commented Aug 7, 2014 at 12:01

3 Answers 3

23

Have you checked the documentation? There is a ReadSingle method in BinaryReader for that.

float value = binaryReader.ReadSingle();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I was looking for ReadFloat () & didnt expect this would return float.
3

You need to read a Single not an Int. If you need an int you can do a cast (int).

MSDN Example

binaryReader.ReadSingle();

Comments

1

You are using read, instead of ReadSingle. I would assume that the read casting into an int is causing some conversion on your data.

See the following documentation articles about Read and ReadSingle

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.