将双精度值存储在二进制文件中并读取它

问题描述 投票:0回答:1

我需要将双精度值存储在二进制文件中并读取它们。我的数据存储在数组中。我尝试了以下代码,但是显然我存储的值比数组大小更多,并且读取的数据完全错误。就像我从array [0]存储0.26一样,我可以看到二进制文件中很少的第一个值是A4 70 3D ...我不知道它是如何将0.26转换为这些值以及基于什么的。

此代码用于写入二进制文件:

  double [] DataCollection_array = new double[10000];

  public void store_data()
   {
    Binary_filename = folder_path + "\\" + "Binary1.bin";
    stream = new FileStream(folder_path + "\\" + "Binary1.bin", FileMode.Create);
    binary_writer = new BinaryWriter(stream);
    writetoBinary(DataCollection_array.size);
   }


  public void writetoBinary(int size)
        {
                for (int i = 0; i < size; i++)
                {
                    binary_writer.Write(DataCollection_array[i]);
                }
         }

此代码用于从包含二进制文件的文件夹中读取双精度值:

  int bytes_counter1 = 0;
  Channels = new List<double>[File_size];

  public void read_data ()
  {
  path2 = Directory2.folder_path + "\\" + "Binary" + file_number + ".bin";
  file_stream = new FileStream(path2, FileMode.Open, FileAccess.Read);
  using (reader = new BinaryReader(file_stream))
         {
          if (bytes_counter1 < reader.BaseStream.Length)
             {
             reader.BaseStream.Seek((count + offset1), SeekOrigin.Begin);
             Channels.Add((double)reader.ReadByte());
             bytes_counter1++;

             }
          }
     }
c# binary hex
1个回答
3
投票

您正在写双打:

binary_writer.Write(DataCollection_array[i]);

但是您只读取字节:

Channels.Add((double)reader.ReadByte()); // Read one byte

将其更改为:

Channels.Add(reader.ReadDouble()); // Read one double
© www.soinside.com 2019 - 2024. All rights reserved.