正在将UTF8转换为Windows-1252

本文关键字:Windows-1252 转换 UTF8 | 更新日期: 2023-09-27 18:28:30

我有一个asp.net GET Web服务,它接受一个URL参数,运行一些逻辑,然后返回一个由þ分隔的值列表。

我遇到的问题是,发出请求的服务使用Windows-1252编码,所以当þ字符返回到请求机器时,它不会正确显示。我正在寻找一种快速的方法来将字符串从UTF8转换为Windows-1252以传递回来。

正在将UTF8转换为Windows-1252

将字符串inputStr转换为字节数组:

byte[] bytes = new byte[inputStr.Length * sizeof(char)];
System.Buffer.BlockCopy(inputStr.ToCharArray(), 0, bytes, 0, bytes.Length);

将其转换为1252:

Encoding w1252 = Encoding.GetEncoding(1252);
byte[] output = Encoding.Convert(utf8, w1252, inputStr);

取回字符串:

w1252.GetString(output);
正如Jon Skeet已经指出的,字符串本身没有编码,只有byte[]有编码。因此,您需要知道哪个编码已应用于字符串,基于此,您可以检索字符串的byte[]并将其转换为所需的编码。然后可以进一步处理得到的byte[](例如,写入文件,在HttpRequest中返回…)
// get the correct encodings 
var srcEncoding = Encoding.UTF8; // utf-8
var destEncoding = Encoding.GetEncoding(1252); // windows-1252
// convert the source bytes to the destination bytes
var destBytes = Encoding.Convert(srcEncoding, destEncoding, srcEncoding.GetBytes(srcString));
// process the byte[]
File.WriteAllBytes("myFile", destBytes); // write it to a file OR ...
var destString = destEncoding.GetString(destBytes); // ... get the string