【问题标题】:Convert from string ascii to string Hex从字符串 ascii 转换为字符串 Hex
【发布时间】:2013-04-01 23:49:47
【问题描述】:

假设我有这个字符串

string str = "1234"

我需要一个将这个字符串转换成这个字符串的函数:

"0x31 0x32 0x33 0x34"  

我在网上搜索了很多类似的东西,但没有回答这个问题。

【问题讨论】:

  • 你能提供第二个例子吗?
  • Possible duplicate: str.ToString("X");
  • 顺便说一句,您的示例不是 ASCII,.NET 字符串是 Unicode (UTF-16)。
  • @vanneto:那行不通。 string 没有采用 string 类型参数的 ToString 重载。

标签: c# string hex ascii


【解决方案1】:
string str = "1234";
char[] charValues = str.ToCharArray();
string hexOutput="";
foreach (char _eachChar in charValues )
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(_eachChar);
    // Convert the decimal value to a hexadecimal value in string form.
    hexOutput += String.Format("{0:X}", value);
    // to make output as your eg 
    //  hexOutput +=" "+ String.Format("{0:X}", value);

}

    //here is the HEX hexOutput 
    //use hexOutput 

【讨论】:

  • 请注意,这使用了string 连接,这可能是也可能不是性能问题,具体取决于str 的大小。
【解决方案2】:

这似乎是扩展方法的工作

void Main()
{
    string test = "ABCD1234";
    string result = test.ToHex();
}

public static class StringExtensions
{
    public static string ToHex(this string input)
    {
        StringBuilder sb = new StringBuilder();
        foreach(char c in input)
            sb.AppendFormat("0x{0:X2} ", (int)c);
        return sb.ToString().Trim();
    }
}

一些提示。
不要使用字符串连接。字符串是不可变的,因此每次连接字符串时都会创建一个新字符串。 (内存使用和碎片压力) StringBuilder 通常在这种情况下更有效。

字符串是字符数组,在字符串上使用 foreach 已经可以访问字符数组

这些通用代码非常适合包含在实用程序库中的扩展方法,始终可用于您的项目(代码重用)

【讨论】:

    【解决方案3】:

    先转换成字节数组再转换成十六进制

            string data = "1234";
    
            // Convert to byte array
            byte[] retval = System.Text.Encoding.ASCII.GetBytes(data);
    
            // Convert to hex and add "0x"
            data =  "0x" + BitConverter.ToString(retval).Replace("-", " 0x");
    
            System.Diagnostics.Debug.WriteLine(data);
    

    【讨论】:

      【解决方案4】:
      static void Main(string[] args)
      {
          string str = "1234";
          char[] array = str.ToCharArray();
          string final = "";
          foreach (var i in array)
          {
              string hex = String.Format("{0:X}", Convert.ToInt32(i));
              final += hex.Insert(0, "0X") + " ";       
          }
          final = final.TrimEnd();
          Console.WriteLine(final);
      }
      

      输出将是;

      0X31 0X32 0X33 0X34
      

      这是DEMO

      【讨论】:

        【解决方案5】:

        解决这个问题的一个很好的声明方式是:

        var str = "1234"
        
        string.Join(" ", str.Select(c => $"0x{(int)c:X}"))
        
        // Outputs "0x31 0x32 0x33 0x34"
        

        【讨论】:

          【解决方案6】:
           [TestMethod]
              public void ToHex()
              {
                  string str = "1234A";
                  var result = str.Select(s =>  string.Format("0x{0:X2}", ((byte)s)));
          
                 foreach (var item in result)
                 {
                     Debug.WriteLine(item);
                 }
          
              }
          

          【讨论】:

          • 输出 0x1、0x2、0x3、0x4。不是 OP 想要的。
          • 您应该删除第一个不正确的版本。你应该修复第二个。它会产生正确的输出,但格式应如下所示:string.Format("0x{0:X2}", (int)s)。原因: (1) X8 从未使用过,因为该参数使用的值是一个字符串。 (2) char 可以包含超出一个字节范围的值。
          • 我只想同时显示 string.Format 和 ToString()。我认为 ASCII 中的字符。字节对于 ascii AFAIK 来说就足够了。谢谢。
          【解决方案7】:

          这是我用过的一个:

          private static string ConvertToHex(byte[] bytes)
                  {
                      var builder = new StringBuilder();
          
                      var hexCharacters = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
          
                      for (var i = 0; i < bytes.Length; i++)
                      {
                          int firstValue = (bytes[i] >> 4) & 0x0F;
                          int secondValue = bytes[i] & 0x0F;
          
                          char firstCharacter = hexCharacters[firstValue];
                          char secondCharacter = hexCharacters[secondValue];
          
                          builder.Append("0x");
                          builder.Append(firstCharacter);
                          builder.Append(secondCharacter);
                          builder.Append(' ');
                      }
          
                      return builder.ToString().Trim(' ');
                  }
          

          然后像这样使用:

          string test = "1234";
          ConvertToHex(Encoding.UTF8.GetBytes(test));
          

          【讨论】:

            猜你喜欢
            • 2016-08-28
            • 2012-01-20
            • 1970-01-01
            • 2020-11-13
            • 1970-01-01
            • 2011-09-06
            • 1970-01-01
            • 1970-01-01
            • 2019-04-12
            相关资源
            最近更新 更多