首页 > 解决方案 > 从另一个字节数组中减去一个字节数组的值

问题描述

我一直在尝试从另一个字节数组中减去一个字节数组的值,这些值是我从文件中读取的。我试图将数组转换为整数,然后减去最终恢复为字节数组的值。

问题是我需要从另一个字节数组中获取值并使用它从另一个字节数组中减去。

我有以下代码,

byte[] arr_i = {0x01,0x02,0x03};
byte[] arr_j = {0x04,0x05,0x06};

    int i = BitConverter.ToInt32(arr_i, 0);
    int j = BitConverter.ToInt32(arr_j, 0);
    int sub = j - i;
    byte[] sum = BitConverter.GetBytes(sub);

一旦我到达 i 变量,我就会得到错误

{"Destination array is not long enough to copy all the items in the collection. Check array index and length."}

在我看来,类型之间存在某种不匹配,但我没有找到任何没有它的例子。

谢谢

标签: c#arraysbinary

解决方案


感谢@Luaan 的评论,我将代码更改为,

byte[] arr_i = {0x01,0x02,0x03,0x04};
byte[] arr_j = {0x04,0x05,0x06,0x07};

int i = BitConverter.ToInt32(arr_i, 0);
int j = BitConverter.ToInt32(arr_j, 0);
int sub = j - i;
byte[] sum = BitConverter.GetBytes(sub);

如预期的那样,总和值为 {0x03, 0x03, 0x03, 0x03}。BitConverter.ToInt32 需要 4 个字节才能按预期运行。


推荐阅读