简体   繁体   中英

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

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 .

这是正常现象,因为您仅添加了0到3范围内的项目。您可以先检查toBuff [someIndex]是否确实具有值,因此不为null。

BitCOnverter.GetBytes返回4个检查数组: http : //msdn.microsoft.com/zh-cn/library/de8fssa4( v=vs.110) .aspx

    toBuff = BitConverter.GetBytes(intNumBuffer);      

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM