0
byte checksum;
byte[] toBuff = new byte[20];
toBuff = BitConverter.GetBytes(intNumBuffer);      
Array.Reverse(mybyte);
checksum = ComputeChecksum(toBuff); //int to byte array

// At this point, the array is something like this
//  toBuff[0] = 25
//  toBuff[1] = 0
//  toBuff[2] = 0
//  toBuff[3] = 0

toBuff[4] = checksum; //HERE IS WHERE OUR OF BOUNDS OCCURS

I am new and would greatly appreciate any help.

Thanks

1
  • What are you trying to do? Commented Sep 17, 2014 at 18:45

3 Answers 3

2
toBuff = BitConverter.GetBytes(intNumBuffer);

The call to BitConverter.GetBytes() returns a byte array of length 4, because intNumBuffer is an int, which has size 4.

So, that means that the valid indices of toBuff are 0, 1, 2 and 3. Hence the error when you use index 4.

Now, I suppose that you imagined that when you wrote:

byte[] toBuff = new byte[20];

that toBuff would have length 20. Well, it does at this point. But when you subsequently overwrite toBuff, then you have a new and different array.

Probably what you need to do is as follows:

byte[] toBuff = new byte[20];
Array.Copy(BitConverter.GetBytes(intNumBuffer), toBuff, sizeof(int)); 

Or perhaps:

byte[] toBuff = new byte[20];
byte[] intBytes = BitConverter.GetBytes(intNumBuffer);
Array.Copy(intBytes, toBuff, intBytes.Length); 

Either of these will copy the bits returned by the call to GetBytes() into toBuff.

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

2 Comments

Thanks for the answer. i just have one question, does that mean my array size changed, and memory of that array was changed to 4 bytes instead of 20, did the other 16 bytes return to free memory.
No, you created a new array. toBuff is a reference.
0

This is normal, because you only add an item in the range of 0 to 3. You could check first if the toBuff[someIndex] actually has a value and thus is not null.

Comments

0

BitCOnverter.GetBytes return an array of 4 check :http://msdn.microsoft.com/en-us/library/de8fssa4(v=vs.110).aspx

    toBuff = BitConverter.GetBytes(intNumBuffer);      

Comments

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.