-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;
}
我感覺很糟糕關於代碼。
的問題是:
- 我能做些什麼來改善功能
byteArrayToStructureArrayB
? - 正如你可以在int24結構中看到的,我有一個叫做
getInt32()
的函數。該功能僅用於結構的位移操作。有沒有更高效的方法?