I have a string, which contains "ä" char. Default encoding I have is 1252. And the char code is 228. How can I convert it to extended ASCII in order to have this char with code 132?
2 Answers
var s = "ä";
var extAscii = Encoding.GetEncoding ("437");
var enc1252 = Encoding.GetEncoding (1252);
var bytes = enc1252.GetBytes (s);
Console.WriteLine (bytes[0]);
var newBytes = Encoding.Convert (enc1252, extAscii, bytes);
Console.WriteLine (newBytes[0]);
This code produces 228, 132. The Extended ASCII aka codepage 437 is pretty exotic these days.
You need to use encoding 437 (see https://en.wikipedia.org/wiki/Code_page_437). This will then correctly convert the extended ASCII symbol "ä" to the corresponding character in ANSI 1252:
using System;
using System.Text;
namespace helloworld
{
public class Program
{
public static void Main(string[] args)
{
string text = "ä";
byte[] bytes = Encoding.GetEncoding(1252).GetBytes(text);
var convertedBytes = Encoding.Convert(Encoding.GetEncoding(1252),Encoding.GetEncoding(437), bytes);
Console.WriteLine(Encoding.GetEncoding(437).GetString(convertedBytes));
}
}
}
5 Comments
Dmitry
No, Encoding.Convert(Encoding.Default, Encoding.ASCII, bytes) gives code "63" (?) instead of "132" (ä).
Alex
Did you try Encoding.GetEncoding(1252) instead of Encoding.Default
Dmitry
Yes, I have spent all day :)
Dmitry
Works? It encodes everything up to 127, then what is over 127 is replaced with 63(?)
Alex
You need to use the codepage 437 for this, see @Andrey post as well