2016-08-16 69 views
-2

在C#中我有一个这样的结构:如何转换C#字节[]为结构[]

[StructLayout(LayoutKind.Sequential,Size = 3)] 
public struct int24 
{ 
     private byte a; 
     private byte b; 
     private byte c; 

     public int24(byte a, byte b, byte c) 
     { 
      this.a = a; 
      this.b = b; 
      this.c = c; 
     } 

     public Int32 getInt32() 
     { 
      byte[] bytes = {this.a, this.b, this.c , 0}; 
      // if we want to put the struct into int32, need a method, not able to type cast directly 
      return BitConverter.ToInt32(bytes, 0); 
     } 

     public void display() 
     { 
      Console.WriteLine(" content is : " + a.ToString() + b.ToString() + c.ToString()); 
     } 
} 

对于byte[]struct[]改造,我使用:

public static int24[] byteArrayToStructureArrayB(byte[] input) { 
     int dataPairNr = input.Length/3; 
     int24[] structInput = new int24[dataPairNr]; 
     var reader = new BinaryReader(new MemoryStream(input)); 

     for (int i = 0; i < dataPairNr; i++) { 
      structInput[i] = new int24(reader.ReadByte(), reader.ReadByte(), reader.ReadByte()); 
     } 

     return structInput; 
} 

我感觉很糟糕关于代码。

的问题是:

  1. 我能做些什么来改善功能byteArrayToStructureArrayB
  2. 正如你可以在int24结构中看到的,我有一个叫做getInt32()的函数。该功能仅用于结构的位移操作。有没有更高效的方法?

回答

0

像这样的东西应该工作:

public struct int24 { 
    public int24(byte[] array, int index) { 
     // TODO: choose what to do if out of bounds 

     a = array[index]; 
     b = array[index + 1]; 
     c = array[index + 2]; 
    } 

    ... 
} 

public static int24[] byteArrayToStructureArrayB(byte[] input) { 
    var count = input.Length/3; 
    var result = new int24[count]; 

    for (int i = 0; i < count; i++) 
     result[i] = new int24(input, i * 3); 

    return result; 
}