【问题标题】:C# - converting a stripped UTF encoded string back to UTFC# - 将剥离的 UTF 编码字符串转换回 UTF
【发布时间】:2016-01-20 18:03:04
【问题描述】:

所以,我有一个字符串,它实际上是 UTF 编码字符,去掉了 ASCII 表示代码: “537465616d6c696e6564” 这将在 ASCII 编码的 UTF 中表示为 \x53\x74\x65 [...]

我尝试在 \x 中的正确位置进行正则表达式替换,对其进行字节编码并将其读回为 UTF,但无济于事。

在 C# 中将 ASCII 字符串转换为可读 UTF 的最有效方法是什么?

【问题讨论】:

    标签: c# encoding utf


    【解决方案1】:

    所以我知道你有一个字符串“537465616d6c696e6564”,它实际上表示char[] chars = { '\x53', '\x74', ... }

    首先将此字符串转换为字节数组How can I convert a hex string to a byte array?

    为了您的方便:

    public static byte[] StringToByteArray(string hex) {
        return Enumerable.Range(0, hex.Length)
                         .Where(x => x % 2 == 0)
                         .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                         .ToArray();
    }
    

    然后还有很多UTF编码(UTF-8、UTF-16),C#内部使用UTF-16(其实是它的子集),所以我假设你想要UTF-16字符串:

    string str = System.Text.Encoding.Unicode.GetString(array);
    

    如果您在解码后得到不正确的字符,您也可以尝试 UTF-8 编码(以防万一您不知道确切的编码,Encoding.UTF8)。

    【讨论】:

    • 谢谢,我显然是在修改字节编码,你的函数工作得更好(TM)。 ;)
    【解决方案2】:

    我不太了解字符串编码,但假设您的原始字符串是一系列字节的十六进制表示,您可以这样做:

    class Program
    {
        private const string encoded = "537465616d6c696e6564";
    
        static void Main(string[] args)
        {
            byte[] bytes = StringToByteArray(encoded);
    
            string text = Encoding.ASCII.GetString(bytes);
    
            Console.WriteLine(text);
            Console.ReadKey();
        }
    
        // From https://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa
        public static byte[] StringToByteArray(String hex)
        {
            int NumberChars = hex.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
            return bytes;
        }
    }
    

    如果您以后想将结果编码为 UTF8,则可以使用:

    Encoding.UTF8.GetBytes(text);
    

    我采用了StringToByteArray 转换的一种实现,但有很多。如果性能很重要,您可能需要选择一个更高效的。有关详细信息,请参阅下面的链接。

    关于字节到字符串的转换(关于性能的一些有趣的讨论):

    .NET 中的字符串

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-13
      • 2011-12-08
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 2015-03-17
      相关资源
      最近更新 更多