0

I want to write a txt file. Some of the chars need to be escaped in a way: \'c1, where c1 is the code of a char in encoding 1251.

How can I convert a given char varialble to string, representing it's code in my encoding?

I found a way to do this for utf, but no way for other ecnodings. For utf variant there is Char.ConvertToUtf32() method.

  • Actually I don't have a code, because I don't know how to achive this. Task grows from the way rtf encodes latin characters. It just escapes it in a way \'c1. – Алексей Медведев Feb 13 '13 at 11:56
  • So, you're trying to put RTF in a text file? – Alex Filipovici Feb 13 '13 at 11:58
  • take a look here http://stackoverflow.com/questions/1951517/convert-a-to-1-b-to-2-z-to-26-and-then-aa-to-27-ab-to-28-column-indexes-to I think this is what you are trying to do or MSDN - http://msdn.microsoft.com/en-us/library/system.char%28v=vs.71%29.aspx – MethodMan Feb 13 '13 at 11:59

2 Answers2

2
// 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;
Paul Ruane
  • 37,459
  • 12
  • 63
  • 82
1

How can I convert a given char varialble to string, representing it's code in my encoding?

Try something like this:

    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)
Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
  • Note that in newer versions of .NET you must call `Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);` before you can use legacy encodings like `Encoding.GetEncoding("Windows-1251")`. – Jeppe Stig Nielsen Oct 25 '21 at 20:07