Decoding an UTF-8 string to Windows-1256

試著忘記壹切 提交于 2019-12-23 19:45:48

问题


I used this code to encode a UTF-8 string to Windows-1256 string:

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

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

        string result = utf.GetString(winByte);

This code is working but I can't decode the result or encoded to original string! How I can decode an encoded string (result variable) to same before converted (q variable)?


回答1:


You are converting the strings incorrectly.

Have a look at the commented code below. The comments explain what is wrong, and how to do it correctly, but basically what is happening is:

Firstly you use Encoding.GetEncoding(1256).GetBytes(q) to convert a string (which is UTF16) to an ANSI codepage 1256 string.

Then you use a UTF7 encoding to convert it back. But that's wrong because you need to use an ANSI codepage 1256 encoding to convert it back:

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


来源:https://stackoverflow.com/questions/17378351/decoding-an-utf-8-string-to-windows-1256

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!