-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()
的函数。该功能仅用于结构的位移操作。有没有更高效的方法?