从另一个字节数组中减去一个字节数组的值

时间:2018-12-12 08:35:41

标签: c# arrays binary

我一直试图从另一个字节数组中减去一个字节数组的值,我从文件中读取了该值。 我试图将数组转换为整数,然后减去该值,最后还原回字节数组。

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

我有以下代码,

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."}

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

谢谢

1 个答案:

答案 0 :(得分:1)

感谢@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个字节才能正常工作。