C# Check if character exists in encoding

Posted by Alvin Wong on Stack Overflow See other posts from Stack Overflow or by Alvin Wong
Published on 2012-06-26T15:12:17Z Indexed on 2012/06/26 15:15 UTC
Read the original article Hit count: 549

Filed under:
|
|
|

I am writing a program that a part renders a bitmap font in CP437.

In a function that renders the text with I want to be able to check whether a char is available in CP437 before the encoding conversion, like:

public static void DrawCharacter(this Graphics g, char c)
{
    if (char_exist_in_encoding(Encoding.GetEncoding(437), c) {
        byte[] src = Encoding.Unicode.GetBytes(c.ToString());
        byte[] dest = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(437), src);
        DrawCharacter(g, dest[0]); // Call the void(this Graphics, byte) overload
    }
}

Without the check, any characters outside CP437 will result in a '?' (63, 0x3F). I want to hide any invalid characters completely. Is there an implementation of char_exist_in_encoding other than the following stupid approach?

public static bool char_exist_in_encoding(Encoding e, char c)
{
    if (c == '?')
        return true;
    byte[] src = Encoding.Unicode.GetBytes(c.ToString());
    byte[] dest = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(437), src);
    if (dest[0] == 0x3F)
        return false;
    return true;
}


Perhaps not very relevant, but the bitmap is created like this:

Bitmap b = new Bitmap(256 * 8, 16);
Graphics g = Graphics.FromImage(b);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
Font f = new Font("Whatever 8x16 bitmap font", 16, GraphicsUnit.Pixel);
for (byte i = 0; i < 255; i++)
{
    byte[] arr = Encoding.Convert(Encoding.GetEncoding(437), Encoding.Unicode, new byte[] { i });
    char c = Encoding.Unicode.GetChars(arr)[0];
    g.DrawString(c.ToString(), f, Brushes.Black, i * 8 - 3, 0); // Don't know why it needs a 3px offset
}
b.Save(@"D:\chars.png");

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET