1

Iv'e been trying to subtract the value of a byte array from another byte array, which values i read from a file. I tried to convert the arrays to integers and then subtract the value finally restoring back to byte array.

The problem is that i need to get the value from another byte array and use that to subtract from another byte array.

I have the following code,

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

Once i get to the i variable i get the error

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

Which seems to me that theres some sort of mismatch between the types, but i didnt find any example of doing this without it.

Thanks

3
  • 2
    Welcome to Stack Overflow. It would be helpful if you could reduce this to a minimal reproducible example - at the moment there are lots of variables involved, many of which I suspect you could remove but still reproduce the problem. Additionally, please post the precise error, and indicate where it occurs. Commented Dec 12, 2018 at 8:41
  • 2
    BitConverter.ToInt32 doesn't convert from byte to int - it reads four bytes from the byte[] you passed and interprets them as an integer. Since your array only has three bytes, this will cause an exception. But to help you fix the problem, we need to see a good example of what you're trying to do. Commented Dec 12, 2018 at 8:48
  • @Luaan Ops, this seems to be a mishap on my part, i didn't notice it needs 4 bytes. I added another byte and it seems to work. So now ill have to see how i change my original code to handle this. Thanks! Commented Dec 12, 2018 at 8:57

1 Answer 1

1

Thanks for @Luaan comment, i changed the code to,

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

And sum value is {0x03, 0x03, 0x03, 0x03} as expected. BitConverter.ToInt32 needed 4 bytes to function as intended.

Sign up to request clarification or add additional context in comments.

1 Comment

Make sure that this behaves the way you want - e.g. with overflows. What should be the result of 0x01020304 - 0x04050607 or 0x04050607 - 0x00060000? This will work fine if you're really trying to subtract two 4-byte integers, but not if e.g. you need to subtract each byte pair individually.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.