Encoding UTF-16 to UTF-8 C#



大家好,我有一些编码问题。我想将utf-16转换为utf-8,我创建了许多代码,但没有工作。我希望能帮助我……由于

This text =>

'x04x1ax040x04@x04Bx040x00 x00*x003x003x000x001x00:x00 x000x001x00.x001x001x00。x002x000x002x002x00 x004x00:x001x000x00,x00 x04?x04>x04;x04=x045x04=x048x045x00 x003x003x00。 x003 x003 x00 x00T x00J x00 x00。x00 x00 x04x14x04>x04Ax04Bx04Cx04?x04=x04>x00 x003x002x002x003'

#I tried this

string v = Regex.Unescape(text);

得到类似

的结果♦→♦♦@ B♦♦0 * 3301:01.11.2022 14:10,♦?♦祝辞♦?♦祝辞♦♦;5 =♦♦= 8♦♦5 33.33套。♦¶♦祝辞♦♦♦♦C B ?♦=♦比;3223

,

public static string Utf16ToUtf8(string utf16String)
{
// Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);
// Return UTF8 bytes as ANSI string
return Encoding.Default.GetString(utf8Bytes);
}

不工作

我需要这样的结果

Карта* 4411:01.11.2022 14:10,пополнение33.33套。Доступно3223

下面的代码将文本解码为您想要的内容,但是如果从一开始就避免陷入这种情况,那么会更好。如果数据基本上是文本,则将其作为文本存储在日志文件中,不需要额外的"转换为UTF-16",然后对二进制数据进行编码;Aspect -这只会引起问题。

下面的代码"解码"。文本通过将每个x转义序列视为单个字节(假设\用于编码反斜杠)并将任何其他字符视为单个字节来将数据记录到字节数组中-有效的ISO-8859-1。

然后使用大端UTF-16将字节数组转换为字符串。输出如下所示:

Карта* 3301:01.11.2022 14:10,пополнение33.33套。Доступно3223

代码确实效率低下——它实际上是一个概念证明,用于验证您得到的文本格式。不要按原样使用;相反,可以将此作为改进存储表示的起点。

using System.Text;
class Program
{
static void Main()
{
string logText = @"x04x1ax040x04@x04Bx040x00 x00*x003x003x000x001x00:x00 x000x001x00.x001x001x00.x002x000x002x002x00 x001x004x00:x001x000x00,x00 x04?x04>x04?x04>x04;x04=x045x04=x048x045x00 x003x003x00.x003x003x00 x00Tx00Jx00Sx00.x00 x00 x04x14x04>x04Ax04Bx04Cx04?x04=x04>x00 x003x002x002x003";
byte[] utf16 = DecodeLogText(logText);
string text = Encoding.BigEndianUnicode.GetString(utf16);
Console.WriteLine(text);
}
static byte[] DecodeLogText(string logText)
{
List<byte> bytes = new List<byte>();
for (int i = 0; i < logText.Length; i++)
{
if (logText[i] == '\')
{
if (i == logText.Length - 1)
{
throw new Exception("Trailing backslash");
}
switch (logText[i + 1])
{
case 'x':
if (i >= logText.Length - 3)
{
throw new Exception("Not enough data for \x escape sequence");
}
// This is horribly inefficient, but never mind.
bytes.Add(Convert.ToByte(logText.Substring(i + 2, 2), 16));
// Consume the x and hex
i += 3;
break;
case '\':
bytes.Add((byte) '\');
// Consume the extra backslash
i++;
break;
// TODO: Any other escape sequences?
default:
throw new Exception("Unknown escape sequence");
}
}
else
{
bytes.Add((byte) logText[i]);
}
}
return bytes.ToArray();
}
}

这对我也有帮助:

string reg = Regex.Unescape(text2);
byte[] ascii = Encoding.BigEndianUnicode.GetBytes(reg);
byte[] utf8 = Encoding.Convert(Encoding.BigEndianUnicode, Encoding.UTF8, ascii);
Console.WriteLine(Encoding.BigEndianUnicode.GetString(utf8));

最新更新