将结构列表转换为字节数组

时间:2010-11-02 20:47:56

标签: c# bytearray

我有一个struct列表,每个struct都有两个short值和一个byte值。我想把它写成一个只包含原始数据的HEX文件。该HEX值将加载到微控制器上。

任何人都可以指出我如何将这些值转储到文件中的正确方向。?

3 个答案:

答案 0 :(得分:1)

我认为通过hex文件你实际上是指二进制文件,而不是带有十六进制代码的文本文件。

结构中会有填充,因此您不能直接将列表转储到文件中。

只需从每个结构中获取值并使用BinaryWriter写入文件:

using (FileStream file = File.OpenWrite("FileName.ext")) {
  using (BinaryWriter writer = new BinaryWriter(file)) {
    foreach (Data data in theList) {
      writer.Write(data.FirstShort);
      writer.Write(data.SecondShort);
      writer.Write(data.TheByte);
    }
  }
}

答案 1 :(得分:1)

假设你的结构是

struct Package {
    public short First { get; private set; }
    public short Second { get; private set; }
    public byte Third { get; private set; }
    public Package(short first, short second, byte third) : this() {
        this.First = first;
        this.Second = second; 
        this.Third = third;
    }
}

然后:

void WritePackageOnWriter(Package package, BinaryWriter binaryWriter) {
    binaryWriter.Write(package.First);
    binaryWriter.Write(package.Second);
    binaryWriter.Write(package.Third);
}

那样

// binaryWriter is BinaryWriter
// packages is IEnumerable<Package>
foreach(var package in packages) {
    WritePackageOnWriter(package, binaryWriter);
}

如有必要,您可以通过

重新构建
Package ReadPackageFromReader(BinaryReader binaryReader) {
    short first = binaryReader.ReadInt16();
    short second = binaryReader.ReadInt16();
    byte third = binaryReader.ReadByte();
    return new Package(first, second, third);
}

答案 2 :(得分:0)

请看这个网站:http://www.developerfusion.com/article/84519/mastering-structs-in-c/

我认为您需要更多地控制数据类型,尤其是使用序列化/反序列化数据。这将允许您完全控制如何编组数据类型。

直接从C#中掌握结构

结构布局

[StructLayout(LayoutKind.Sequential,
Pack = 1, CharSet = CharSet.Unicode)]
public struct DISPLAY_DEVICE
{
    public int cb;
    [MarshalAs(
        UnmanagedType.ByValArray,
        SizeConst=32)]
        public char[] DeviceName;
    [MarshalAs(
        UnmanagedType.ByValArray,
        SizeConst=128)]
        public char[] DeviceString;
    public int StateFlags;
    [MarshalAs(
        UnmanagedType.ByValArray,
        SizeConst = 128)]
        public char[] DeviceID;
    [MarshalAs(
        UnmanagedType.ByValArray,
        SizeConst = 128)]
        public char[] DeviceKey;
}

<强>序列化

public static byte[]
    RawSerialize(object anything)
{
    int rawsize =
        Marshal.SizeOf(anything);
    IntPtr buffer =
        Marshal.AllocHGlobal(rawsize);
    Marshal.StructureToPtr(anything,
        buffer, false);
    byte[] rawdata = new byte[rawsize];
    Marshal.Copy(buffer, rawdata,
        0, rawsize);
    Marshal.FreeHGlobal(buffer);
    return rawdata;
}

旁注:

对于基本的序列化,我不会尝试自己使用我只使用内置的.NET序列化:http://msdn.microsoft.com/en-us/library/4abbf6k0.aspx