因此,我有一个字符串,实际上是UTF编码字符,去掉了ASCII表示代码:"537465616d6c696e6564“这将在ASCII编码的UTF中表示为\x53\x74\x65 .
我尝试过将Regexp替换到正确的位置,对其进行字节编码,并将其读取为UTF,但没有结果。
在C#中将ASCII字符串转换为可读UTF的最有效方法是什么?
发布于 2016-01-20 18:18:06
因此,据我所知,您有一个字符串"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)。
发布于 2016-01-20 18:50:41
我对字符串编码不太了解,但是假设您的原始字符串是一系列字节的十六进制表示,您可以这样做:
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中的字符串
https://stackoverflow.com/questions/34907290
复制相似问题