我在通过 BitConverter.ToInt32 将字节数组转换为 int32 时遇到问题。
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: Destination array is not long enough to copy all the items in the > collection. Check array index and length
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
很少有用。
另外,在编码风格方面:
- 您正在分配一个新的字节数组,但实际上忽略了它
- 您在实际使用变量之前就先声明了变量,没有任何理由。 (最好在第一次使用时声明变量)
- 您的变量不遵循 .NET 命名约定,在这些命名约定中它们将采用驼峰式命名,理想情况下提供更多的意义指示而不仅仅是类型
因此,即使您的代码实际上是正确的,也最好写成:
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
不理想 - 如果我们知道您试图将其与值,我们可以在变量名中使用它。)
关于c# - 将字节数组转换为 int32,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19784085/