简体   繁体   English

将UTF8转换为Windows-1252

[英]Converting UTF8 to Windows-1252

I have an asp.net GET webservice that takes in a URL parameter, runs some logic, and then passes back a þ delimited list of values. 我有一个asp.net GET Web服务,它接受URL参数,运行一些逻辑,然后传回a分隔的值列表。

The problem I have is the service making the request is using Windows-1252 encoding, so the þ character doesn't display properly when it's returned to the requesting machine. 我遇到的问题是发出请求的服务使用Windows-1252编码,因此将when字符返回给请求计算机时,machine字符无法正确显示。 I'm looking for a quick way to convert a string from UTF8 to Windows-1252 to pass back. 我正在寻找一种将字符串从UTF8转换为Windows-1252并传递回去的快速方法。

Convert your string inputStr to byte array : 将您的字符串inputStr转换为字节数组:

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

Convert it to 1252: 将其转换为1252:

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

Get the string back: 取回字符串:

w1252.GetString(output);

As Jon Skeet already pointed out, the string itself has no encoding, it's the byte[] that has an encoding. 正如Jon Skeet所指出的那样,字符串本身没有编码,只有byte[]有编码。 So you need to know which encoding has been applied to your string, based on this you can retrieve the byte[] for the string and convert it to the desired encoding. 因此,您需要知道对字符串应用了哪种编码,基于此,您可以检索字符串的byte[]并将其转换为所需的编码。 The resulting byte[] can then be further processed (eg written to a file, returned in a HttpRequest, ...). 然后可以对所得的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM