最近用c#解析二进制文件,以下是代码:
FileStream fs = new FileStream(@"F:\1.dat", FileMode.Open);            BinaryReader br = new BinaryReader(fs, Encoding.GetEncoding("gb2312"));            for (int j = 0; j < (fs.Length) / 156; j++)//156是结构体的总字节数大小
            {
                long ltine = br.ReadInt32();                DateTime stocktime= UTCToDateTime(ltine);                byte[] byte_code = br.ReadBytes(12);
                string strcode = Encoding.Default.GetString(byte_code).TrimEnd('\0');                byte[] byte_name = br.ReadBytes(15);
                string strname = Encoding.Default.GetString(byte_name).TrimEnd('\0');                short flag = br.ReadInt16();                float preJieSuanPrice = br.ReadSingle();
                //byte[] byte_preJieSuanPrice = br.ReadBytes(4);
                //float preJieSuanPrice = BitConverter.ToSingle(byte_preJieSuanPrice,0);                ......            }读到这里就有问题了,
float preJieSuanPrice = br.ReadSingle();
正常值应该是720.75000,但这里读出的是6.263535E-39,请问是方法不对吗?还是?

解决方案 »

  1.   

    既然是定长结构的,那就读固定大小的块,放到结构体的内存区好了,用Marshal或unsafe的结构体。
      

  2.   

    FileStream fs = new FileStream(@"F:\1.dat", FileMode.Open);
    BinaryReader br = new BinaryReader(fs);byte[] buffer= br.ReadBytes((int)fs.Length);
    youStruct=(youStruct)BytesToStruct(buffer,youStruct.GetType());//得到你结构体
    。。br.Close();
    fs.Close();
    public Object BytesToStruct(Byte[] bytes, Type strcutType)
    {
                Int32 size = Marshal.SizeOf(strcutType);
                IntPtr buffer = Marshal.AllocHGlobal(size);
                try
                {
                    Marshal.Copy(bytes, 0, buffer, size);
                    return Marshal.PtrToStructure(buffer, strcutType);
                }
                finally
                {
                    Marshal.FreeHGlobal(buffer);
                }
    }
      

  3.   

    这样读好像不保险,至少读完一个结构后,seek一下位置 保险点儿吧
      

  4.   

    2楼的方法试了下,和我的方法得到的结果一样,问题都出在float字段上
      

  5.   

    float preJieSuanPrice = br.ReadSingle();
       //byte[] byte_preJieSuanPrice = br.ReadBytes(4);你把这四个字节的内容贴出来看看
      

  6.   

    你贴了个缩略图,还好地址里包括了原图。你读出来的是48,52,68,0,但是float值 720.75转换为字节是0,48,52,68,所以,可能是你读的偏移量靠后了一个字节,你看看前面哪个多读了一个字节。