[英]Convert byte array to int32
我有一個問題,通過BitConverter.ToInt32將字節數組轉換為int32。
mscorlib.dll中出現未處理的“System.ArgumentException”類型異常
附加信息:目標數組不夠長,無法復制>集合中的所有項目。 檢查數組索引和長度
private void textBox2_TextChanged(object sender, EventArgs e)
{
byte[] StrToByte = new byte[9];
int IntHexValue;
StrToByte = Encoding.UTF8.GetBytes(textBox2.Text);
textBox4.Text = BitConverter.ToString(StrToByte);
IntHexValue = BitConverter.ToInt32(StrToByte, 0);
}
據推測, textBox2
本的UTF-8表示長度少於4個字節。 BitConverter.ToInt32
需要4個字節的數據才能使用。
順便說一句,目前還不清楚你想要實現的目標 - 但在編碼文本上使用BitConverter.ToInt32
很少是有用的事情。
另外,在編碼風格方面:
所以,即使你的代碼實際上是正確的,這將是更好的寫法如下:
private void textBox2_TextChanged(object sender, EventArgs e)
{
byte[] encodedText = Encoding.UTF8.GetBytes(textBox2.Text);
textBox4.Text = BitConverter.ToString(encodedText);
int leadingInt32 = BitConverter.ToInt32(encodedText, 0);
// Presumably use the value here...
}
(正如我所說,目前還不清楚你真正想要做什么,這就是為什么名稱leadingInt32
不理想 - 如果我們知道你試圖與值相關聯的意思,我們可以在變量名中使用它。)
這個錯誤的原因是BitConverter.ToInt32
需要至少4個元素的字節數組,但是你傳遞給它的結果是Encoding.UTF8.GetBytes(textBox2.Text)
,如果用戶鍵入的內容很短,則可以少於4個字節textBox2
,例如“123” - 它只有3個字節。 作為場景的解決方法,您應該將字節數組填充至少4個字節長,如下所示:
StrToByte = Encoding.UTF8.GetBytes("123");
if (StrToByte.Length < 4)
{
byte[] temp = new byte[4];
StrToByte.CopyTo(temp, 0);
StrToByte = temp;
}
IntHexValue = BitConverter.ToInt32(StrToByte, 0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.