[英]Convert int to different size of byte array
I have a byte array result
. 我有一个字节数组result
。 I would like to convert my type called Info
which are all int
to the byte array but all of them are in different size. 我想转换我的类型,称为Info
这都int
的字节数组,但所有的人都在不同的大小。
a = 4 bytes a = 4个字节
b = 3 bytes b = 3个字节
c = 2 bytes c = 2个字节
d = 1 bytes d = 1个字节
This is the code I've tried. 这是我尝试过的代码。
private byte[] getInfoByteArray(Info data)
{
byte[] result = new byte[10];
BitConverter.GetBytes((data.a)).CopyTo(result, 0);
BitConverter.GetBytes((data.b)).CopyTo(result, 4);
BitConverter.GetBytes((data.c)).CopyTo(result, 7);
result [9] = Convert.ToByte(data.d);
return result;
}
However, I found out that BitConverter.GetBytes
returns 4 bytes. 但是,我发现BitConverter.GetBytes
返回4个字节。
Are there any general solutions that can get different size of bytes to a byte array? 是否有任何通用的解决方案可以使字节数组获得不同的字节大小?
Use Array.Copy(Array, Int32, Array, Int32, Int32)
method: 使用Array.Copy(Array, Int32, Array, Int32, Int32)
方法:
byte[] result = new byte[10];
Array.Copy(BitConverter.GetBytes(data.a), 0, result, 0, 4);
Array.Copy(BitConverter.GetBytes(data.b), 0, result, 4, 3);
Array.Copy(BitConverter.GetBytes(data.c), 0, result, 7, 2);
Array.Copy(BitConverter.GetBytes(data.d), 0, result, 9, 1);
This assumes little endian hardware. 这假设没有端序硬件。 If your hardware is big endian, use 如果您的硬件是大端,请使用
byte[] result = new byte[10];
Array.Copy(BitConverter.GetBytes(data.a), 0, result, 0, 4);
Array.Copy(BitConverter.GetBytes(data.b), 1, result, 4, 3);
Array.Copy(BitConverter.GetBytes(data.c), 2, result, 7, 2);
Array.Copy(BitConverter.GetBytes(data.d), 3, result, 9, 1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.