2016-08-16 3 views
-2

In C# Ich habe eine Struktur wie folgt zu transformieren:Wie C# byte [] auf struct []

[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()); 
     } 
} 

Für byte[] zu struct[] Transformation, die ich benutze:

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; 
} 

Ich fühle mich wirklich schlecht über den Code.

Fragen sind:

  1. Was kann ich die Funktion byteArrayToStructureArrayB zu verbessern? Wie Sie in der Struktur int24 sehen können, habe ich eine Funktion namens getInt32(). Diese Funktion dient nur zur Bit-Shift-Operation der Struktur. Gibt es einen effizienteren Weg?

Antwort

0

So etwas sollte funktionieren:

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; 
}