3

我使用此代码将 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 变量)?

4

1 回答 1

4

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

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

首先,您用于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
于 2013-06-29T09:22:20.407 回答