c# - 将字节数组转换为 int32

标签 c# winforms

我在通过 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/

相关文章:

.net - 如何在 VB.Net winforms 应用程序中找到 main() 入口点?

C# 从 System.Threading.Timer tick 创建表单失败

c# - 我的命名空间的名称与 .net 框架命名空间相同

c# - 这是防守加成吗? ".SynchronizingObject =this;"

c# - 如何创建按月份排序的图表?

c# - 调试 Windows 服务

vb.net - 无法在 dropdownList 控件中显示记录

c# - 如果我真的不需要它们,是否应该获取所有数据库表字段?

c# - 将子类添加到 List<parent> 时,特定于子类的数据是否丢失?

c# - 从 JsonReader 读取 JObject 时出错。当前 JsonReader 项不是对象 : StartArray. 路径