【问题标题】:Decoding an UTF-8 string to Windows-1256将 UTF-8 字符串解码为 Windows-1256
【发布时间】:2013-06-29 08:41:31
【问题描述】:

我使用此代码将 UTF-8 字符串编码为 Windows-1256 字符串:

        string q = textBox1.Text;
        UTF7Encoding utf = new UTF7Encoding();

        byte[] winByte = Encoding.GetEncoding(1256).GetBytes(q);

        string result = utf.GetString(winByte);

此代码有效,但我无法解码结果或编码为原始字符串! 如何在转换之前将编码字符串(结果变量)解码为相同(q 变量)?

【问题讨论】:

  • 您的标题是 UTF-8,但您的代码是 UTF-7...?另外,您知道编码是如何工作的吗?
  • 我通过测试和错误找到了上面的代码。我想编写一个文本框以在狐猴项目中使用,然后解码结果狐猴在其他文本框中显示。上面代码的编码效果很好,但我无法解码结果。

标签: c# encoding utf-8 decoding


【解决方案1】:

您正在错误地转换字符串。

看看下面的注释代码。 cmets 解释了什么是错误的,以及如何正确地做,但基本上发生了什么是:

首先,您使用Encoding.GetEncoding(1256).GetBytes(q) 将字符串(即UTF16)转换为ANSI 代码页1256 字符串。

然后您使用 UTF7 编码将其转换回来。但这是错误的,因为您需要使用 ANSI 代码页 1256 编码将其转换回来:

string q = "ABئبئ"; // UTF16.
UTF7Encoding utf = new UTF7Encoding(); // Used to convert UTF16 to/from UTF7

// Convert UTF16 to ANSI codepage 1256. winByte[] will be ANSI codepage 1256.
byte[] winByte = Encoding.GetEncoding(1256).GetBytes(q);

// Convert UTF7 to UTF16.
// But this is WRONG because winByte is ANSI codepage 1256, NOT UTF7!
string result = utf.GetString(winByte);

Debug.Assert(result != q); // So result doesn't equal q

// The CORRECT way to convert the ANSI string back:
// Convert ANSI codepage 1256 string to UTF16

result = Encoding.GetEncoding(1256).GetString(winByte);

Debug.Assert(result == q); // Now result DOES equal q

【讨论】:

  • 您假设您有一个由 utf.GetString(winByte) 编码的结果变量,如何在没有原始文本的情况下进行解码。实际上,狐猴的函数的结果是这样编码的。
  • @user1490377 不确定您的意思。您不需要原始文本来解码,您只需要要解码的数据字节以及使用哪个解码器的知识。
猜你喜欢
  • 2018-09-30
  • 1970-01-01
  • 1970-01-01
  • 2019-09-15
  • 2015-05-09
  • 2011-08-09
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
相关资源
最近更新 更多