繁体   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

我是新手,不胜感激。

谢谢

toBuff = BitConverter.GetBytes(intNumBuffer);

调用BitConverter.GetBytes()返回一个长度为4的字节数组,因为intNumBuffer是一个int ,大小为4。

因此,这意味着toBuff的有效索引为toBuff和3。因此,使用索引4时出错。

现在,我想您在编写时就想到了:

byte[] toBuff = new byte[20];

toBuff长度为20。 但是,当您随后覆盖toBuff ,您将拥有一个新的且不同的数组。

您可能需要做的如下:

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

也许:

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

这些方法中的任何一个都会将对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