代码之家  ›  专栏  ›  技术社区  ›  Kenneth Aalberg

C#-将剥离的UTF编码字符串转换回UTF

  •  1
  • Kenneth Aalberg  · 技术社区  · 9 年前

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

    我尝试过用Regexp替换in\x中的正确位置,对其进行字节编码,并将其读回UTF,但没有成功。

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

    2 回复  |  直到 9 年前
        1
  •  1
  •   Community CDub    7 年前

    我所理解的是,你有一个字符串“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的子集),所以我假设您需要UTF-16字符串:

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

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

        2
  •  0
  •   Community CDub    7 年前

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

    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中的字符串上