2016-08-16 77 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; 
}