是否可以将此代码简化为更干净/更快的形式?
StringBuilder builder = new StringBuilder();
var encoding = Encoding.GetEncoding(936);
// convert the text into a byte array
byte[] source = Encoding.Unicode.GetBytes(text);
// convert that byte array to the new codepage.
byte[] converted = Encoding.Convert(Encoding.Unicode, encoding, source);
// take multi-byte characters and encode them as separate ascii characters
foreach (byte b in converted)
builder.Append((char)b);
// return the result
string result = builder.ToString();
简单来说,就是将包含郓等汉字的字符串转换为ài。
例如,该汉字十进制为37126,十六进制为0x9106。
See http://unicodelookup.com/#0x9106/1 http://unicodelookup.com/#0x9106/1
转换为字节数组,我们得到 [145, 6] (145 * 256 + 6 = 37126)。当以 CodePage 936(简体中文)编码时,我们得到 [224, 105]。如果我们将这个字节数组分解为单个字符,则在 unicode 中我们可以得到 224=e0=à 和 105=69=i。
See http://unicodelookup.com/#0x00e0/1 http://unicodelookup.com/#0x00e0/1
and
http://unicodelookup.com/#0x0069/1 http://unicodelookup.com/#0x0069/1
因此,我们正在进行编码转换并确保输出 Unicode 字符串中的所有字符都可以使用最多两个字节来表示。
更新:我需要这个最终表示,因为这是我的收据打印机接受的格式。我花了很长时间才弄清楚! :) 由于我不是编码专家,我正在寻找更简单或更快的代码,但输出必须保持不变。
更新(清洁版本):
return Encoding.GetEncoding("ISO-8859-1").GetString(Encoding.GetEncoding(936).GetBytes(text));