【问题标题】:How to input comma separated Hex values into a textbox and output as hex values, c#如何将逗号分隔的十六进制值输入到文本框中并输出为十六进制值,c#
【发布时间】:2014-12-18 09:40:23
【问题描述】:

这是我到目前为止为此提出的代码,但是当我输入字母值(例如 AA)时,它会引发此异常。

“在 mscorlib.dll 中发生了“System.FormatException”类型的未处理异常附加信息:输入字符串的格式不正确。”

如果用户输入无效值,我还想包含一些错误消息。任何帮助都会很棒,谢谢。

               private void GPIO_Click(object sender, EventArgs e)
                {
                    string hex = WriteValue.Text;
                    string[] hex1 = hex.Split(',');
                    byte[] bytes = new byte[hex1.Length];

                    for (int i = 0; i < hex1.Length; i++)
                    {
                        bytes[i] = Convert.ToByte(hex1[i]);
                    }

                    for (int i = 0; i < hex1.Length; i++)
                    {
                    GPIO(h[index], dir, bytes[i]);
                    ReadValue.Text += bytes[i].ToString();
                    }
                 }

【问题讨论】:

    标签: c# textbox hex windows-forms-designer


    【解决方案1】:

    您需要在基数设置为 16(十六进制)的情况下调用它。

    Convert.ToByte(text, 16)
    

    很多重复:

    c# string to hex , hex to byte conversion

    How do you convert Byte Array to Hexadecimal String, and vice versa?

    【讨论】:

    • 有趣的是,当答案如此简单时,它是多么容易令人困惑。 +1
    【解决方案2】:

    当你到达时

    bytes[i] = Convert.ToByte(hex1[i]);
    

    hex1[i] 的值为"AA"

    您的应用程序在此处失败,因为您无法将“AA”作为单个字节的字符串。

    如果您正在寻找字符串的字节数组转换, 您将希望将该值拆分为 chars ;像这样:

      string hex = "AA";
      string[] hex1 = hex.Split(',');
      List<byte[]> byteArrays = List<byte[]>();
    
      foreach (string t in hex1)
      {
            int byteIndex = 0;
            byte[] newArray = new byte[hex1.Length];
            foreach(char c in t)
            {
                  newArray [byteIndex] = Convert.ToByte(c);
                  byteIndex++;
            }
            byteArrays.add(newArray);
      }
    

    但我不认为那是你所追求的。您正在寻找以字符串表示的十进制值。

    【讨论】:

    • 哦,等等。我不太明白 OP 想要达到的目标。
    猜你喜欢
    • 2019-07-28
    • 2015-02-18
    • 2018-07-26
    • 2014-11-30
    • 2011-08-04
    • 1970-01-01
    • 2016-07-25
    • 2011-12-09
    • 2017-01-18
    相关资源
    最近更新 更多