将字节数组转换为int32

use*_*372 4 c# winforms

我有一个问题,通过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);
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

据推测,文本的UTF-8表示textBox2长度少于4个字节.BitConverter.ToInt32需要4个字节的数据才能使用.

顺便说一句,目前还不清楚你想要实现的目标 - 但使用BitConverter.ToInt32编码文本很少是有用的事情.

另外,在编码风格方面:

  • 你正在分配一个新的字节数组,但后来却有效地忽略了它
  • 你无意中在实际使用之前声明了变量.(理想情况下,在首次使用时声明变量)
  • 您的变量不遵循.NET命名约定,它们将基于camelCased并且理想情况下提供更多的含义指示而不仅仅是类型

所以,即使你的代码实际上是正确的,这将是更好的写法如下:

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...
}
Run Code Online (Sandbox Code Playgroud)

(正如我所说,目前还不清楚你真正想要做什么,这就是为什么名称leadingInt32不理想 - 如果我们知道你试图与价值联系的意义,我们可以在变量名中使用它. )