如何将字节数组从二进制文件复制到struct数组。 [英] How to copy byte array from binary file to array of struct.

查看:97
本文介绍了如何将字节数组从二进制文件复制到struct数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定大小的二进制文件。这个文件包含96个不同类型的记录,如下面的结构。

文件:exam.dat

  public   struct 考试
{
double DATA1;
double data2;
单个数据3;
int data4;
double data5;
}

public 考试[]记录= 考试[ 96 ];







我可以通过使用binaryReader或streamreader和数据保持字节数组格式来读取它,怎么能我复制到struct数组。

解决方案

一个简单的方法是为你的struct提供一个接受一个字节数组的构造函数。这样的结构将反复使用 BitConverter类 [ ^ ](例如,您可以使用 data1 = BitConverter.ToDouble(ba,0); 其中 ba 是你的字节数组。)


你可以使用转换器。



双倍:



  var  index =  0 ; 
考试[index] .data1 = BitConverter.ToDouble(byteArr, 0 );
// 为data2,data3做。 。 。
index ++;
。 。


I''ve a fixed size of binary file. This file was contain 96 record with different type like a struct below.
file : "exam.dat"

public struct Exam
{
    double  data1;
    double  data2;
    single  data3;
    int     data4;
    double  data5;
}

public Exam[] record = new Exam[96];     




I can read it by using binaryReader or streamreader and data keep in byte array format, how can i copy into array of struct.

解决方案

A simple approach would be providing a contructor for your struct accepting an array of bytes. Such a conctructor would use repeatedly the BitConverter class[^] (for instance you may use data1 = BitConverter.ToDouble( ba, 0); where ba is your byte array).


You can use a converter.

For double:

var index = 0;
Exam[index].data1 = BitConverter.ToDouble(byteArr, 0);
//do it for data2, data3 . . .
index++;
. . .


这篇关于如何将字节数组从二进制文件复制到struct数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆