Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将UTF-8字符串解码为Windows-1256_C#_Encoding_Utf 8_Decoding - Fatal编程技术网

C# 将UTF-8字符串解码为Windows-1256

C# 将UTF-8字符串解码为Windows-1256,c#,encoding,utf-8,decoding,C#,Encoding,Utf 8,Decoding,我使用此代码将UTF-8字符串编码为Windows-1256字符串: string q = textBox1.Text; UTF7Encoding utf = new UTF7Encoding(); byte[] winByte = Encoding.GetEncoding(1256).GetBytes(q); string result = utf.GetString(winByte); 此代码正在工作,但我无法解码结果或编

我使用此代码将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变量)之前将编码字符串(结果变量)解码为相同的字符串?

您正在错误地转换字符串

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

首先,使用
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-8,但你的代码是UTF-7。。。?另外,你知道编码是如何工作的吗?我通过测试和错误发现了上面的代码。我想编码一个文本框用于狐猴项目,然后解码结果狐猴显示在其他文本框。通过上面的代码进行编码,它工作得很好,但我无法解码结果。您假设您有一个结果变量,该变量由utf.GetString(winByte)编码,如何在没有原始文本的情况下进行解码。实际上,lemur函数的结果是这样编码的。@user1490377不确定您的意思。解码时不需要原始文本,只需要解码的数据字节和使用哪个解码器的知识。