【问题标题】:Convert int to different size of byte array将 int 转换为不同大小的字节数组
【发布时间】:2016-09-07 02:17:21
【问题描述】:

我有一个字节数组result。我想将我的名为Info 的类型全部转换为int 到字节数组,但它们的大小都不同。

a = 4 个字节

b = 3 个字节

c = 2 个字节

d = 1 个字节

这是我尝试过的代码。

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

但是,我发现BitConverter.GetBytes 返回 4 个字节。

是否有任何通用解决方案可以将不同大小的字节转换为字节数组?

【问题讨论】:

  • int 始终存储为 4 个字节。 GetBytes() 并不总是只返回 4 长的字节数组,它这样做只是因为您使用的是 int 数据类型。您可以使用this answer 计算保存整数值所需的最小字节数(假定返回列出的 4、3、2 和 1 大小),然后在复制到之前将.GetBytes() 的结果修剪到该长度你的最终字节数组。
  • 不清楚为什么要为字段设置不同的字节长度,尤其是当它们实际上都是 int 类型时。如果您确定 b、c 和 d 确实只需要 3、2 或 1 个字节,那么 c 和 d 可以是 shortbyte,这正是您所需要的。您对 b 的结果取决于字节顺序,但您可以截断数组,例如Array.Copy(BitConverter.GetBytes(data.b), 0, result, 4, 3)。 IE。如果您不想要所有字节,则不要复制所有字节

标签: c# byte bytearray


【解决方案1】:

使用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);

这假设是小端硬件。如果您的硬件是大端,请使用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 2016-12-31
    • 2010-10-22
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多