【问题标题】:C# Hexadecimal to charC# 十六进制转char
【发布时间】:2022-12-20 18:55:02
【问题描述】:

我有一个长度为4的十六进制字符串,比如“003a”。

将其转换为 char 的最佳方法是什么?先转bytes再转char?

【问题讨论】:

    标签: c#


    【解决方案1】:

    试试这个:

    (char)Int16.Parse("003a", NumberStyles.AllowHexSpecifier);
    

    或者

    System.Convert.ToChar(System.Convert.ToUInt32("003a", 16));
    

    要么

    string str = "";
    for(int i = 0; i<myHex.Length; i += 4)
        str += (char)Int16.Parse(myHex.Substring(i, 4), 
                                 NumberStyles.AllowHexSpecifier);
    

    【讨论】:

    • 谢谢。这是工作代码: char hexchar = (char)Int16.Parse("003a", NumberStyles.AllowHexSpecifier);
    • System.Convert.ToUInt32("003a")-->System.Convert.ToUInt32("003a",16)
    • 在 System.Convert.ToChar(System.Convert.ToUInt32("003a"));您需要向 ToUInt32 提供第二个参数,例如 System.Convert.ToChar(System.Convert.ToUInt32("003a", 16));
    【解决方案2】:

    2020年我会这样做

    char c = (char)0x3A;
    

    如果我需要它是一个用于删除不可打印字符的字符串,它会像这样

    s = s.Replace($"{(char)0x3A}", ""));
    

    【讨论】:

      【解决方案3】:

      您可以使用以下代码:

      label1.Text = System.Convert.ToChar(System.Convert.ToUInt32("0x00AC", 16)).ToString();
      

      【讨论】:

        【解决方案4】:

        首先使用 Int32.Parse() 解析它,然后使用 Convert.ToChar()

        【讨论】:

          猜你喜欢
          • 2018-11-07
          • 2011-05-25
          • 2012-02-24
          • 2013-05-07
          • 2011-10-13
          • 2018-08-16
          • 2013-09-01
          • 2011-10-28
          • 2018-11-18
          相关资源
          最近更新 更多