Why BinaryReader.ReadDecimal() returns wrong value?

时间:2019-04-08 13:32:08

标签: c# stream

I stored data type values into a file then consumes it but I get the wrong result. What do I need to do get the right result?

        BinaryWriter bw = new BinaryWriter(file.OpenWrite());
        string str = "Lalisa";
        int num = 10;
        decimal dec = 2;
        bw.Write(str);
        bw.Write(num);
        bw.Write(dec);
        bw.Close();

        BinaryReader br = new BinaryReader(file.OpenRead());
        Console.WriteLine(br.ReadString()); 
        Console.WriteLine(br.ReadInt16());
        Console.WriteLine(br.ReadDecimal());
        br.Close();

        /*
         output:
         Lalisa
         10
         131072
         */

Writer output

produced file by the writer

Note* I'm using FileInfo class for the stream. The purpose of this is for studying I'm not trying to solve a problem for a project.

1 个答案:

答案 0 :(得分:4)

The problem is the below line

Console.WriteLine(br.ReadInt16());

You are writing a 32 bit integer, and reading only 16 bits back, causing a problem for the subsequent reads.

You should have

Console.WriteLine(br.ReadInt32());

This should fix your issue

Explanation:

The bytes are written in Little Endian format, so the 10 int and 2 decimal are written as follows. Square brackets are for marking the start and end of the int and the decimal

[0A 00 00 00] [02 00 00 00...00]

But when you read the int as just a 16 bit value, this is how you will group the bits to read

[0A 00] [00 00 02 00 00 00...00]

As you can notice, the int does not suffer in this process and is still read as 0x000A, but the decimal got shifted by 2 bytes, switching it from 0x02 to 0x020000 which is 131702 in decimal

If the format was big endian, then you would have see the int get the incorrect value of 0x00