[英]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.