简体   繁体   English

字节数组中的C#元素未能初始化,空字节未能初始化

[英]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. 调用BitConverter.GetBytes()返回一个长度为4的字节数组,因为intNumBuffer是一个int ,大小为4。

So, that means that the valid indices of toBuff are 0, 1, 2 and 3. Hence the error when you use index 4. 因此,这意味着toBuff的有效索引为toBuff和3。因此,使用索引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. toBuff长度为20。 But when you subsequently overwrite toBuff , then you have a new and different array. 但是,当您随后覆盖toBuff ,您将拥有一个新的且不同的数组。

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 . 这些方法中的任何一个都会将对GetBytes()的调用返回的位复制到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);      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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