Sam
Sam

Reputation: 51

C# element in byte array fails to be initialize, null byte fails to initialize

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

Upvotes: 0

Views: 395

Answers (3)

David Heffernan
David Heffernan

Reputation: 612894

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.

Upvotes: 2

Ahmad Al Sayyed
Ahmad Al Sayyed

Reputation: 596

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

    toBuff = BitConverter.GetBytes(intNumBuffer);      

Upvotes: 0

user2153378
user2153378

Reputation:

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.

Upvotes: 0

Related Questions