我想写一个txt文件。某些字符需要以某种方式转义:\'c1,其中 c1 是编码 1251 中字符的代码。
如何将给定的 char 变量转换为字符串,在我的编码中表示它的代码?
我找到了一种对 utf 执行此操作的方法,但对于其他 ecnodings 没有办法。对于 utf 变体,有 Char.ConvertToUtf32() 方法。
// get the encoding
Encoding encoding = Encoding.GetEncoding(1251);
// for each character you want to encode
byte b = encoding.GetBytes("" + c)[0];
string hex = b.ToString("x");
string output = @"\'" + hex;
如何将给定的 char 变量转换为字符串,在我的编码中表示它的代码?
尝试这样的事情:
var enc = Encoding.GetEncoding("Windows-1251");
char myCharacter = 'д'; // Cyrillic 'd'
byte code = enc.GetBytes(new[] { myCharacter, })[0];
Console.WriteLine(code.ToString()); // "228" (decimal)
Console.WriteLine(code.ToString("X2")); // "E4" (hex)