-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:
- Was kann ich die Funktion
byteArrayToStructureArrayB
zu verbessern? Wie Sie in der Struktur int24 sehen können, habe ich eine Funktion namensgetInt32()
. Diese Funktion dient nur zur Bit-Shift-Operation der Struktur. Gibt es einen effizienteren Weg?