【问题标题】:Check if character exists in encoding检查编码中是否存在字符
【发布时间】:2012-06-26 15:12:17
【问题描述】:

我正在编写一个程序,其中一部分在 CP437 中呈现位图字体。

在呈现文本的函数中,我希望能够在编码转换之前检查char 在 CP437 中是否可用,例如:

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
    }
}

如果不进行检查,CP437 之外的任何字符都将导致'?' (63, 0x3F)。我想完全隐藏任何无效字符。是否有char_exist_in_encoding 的实现除了以下愚蠢的方法

private 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, e, src);
    if (dest[0] == 0x3F)
        return false;
    return true;
}


也许不是很相关,但是位图是这样创建的:

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");

【问题讨论】:

  • @JohnSaunders 谢谢,会记住的
  • 也许你需要EncoderFallback
  • CP437 之外的角色的示例是什么?我尝试将每个字节从 0 转换为 254,它们似乎都可以工作。
  • @MichaelLiu 大多数 Unicode 字符,如中文、日文、韩文等

标签: c# .net encoding character-encoding


【解决方案1】:

感谢 Vlad,在对EncoderFallback 进行了一些研究之后,我终于看到了an example in MSDN

我的工作(可能是临时工作)代码是:

public static void DrawCharacter(this Graphics g, char c)
{
    byte[] src = Encoding.Unicode.GetBytes(c.ToString());
    byte[] dest = Encoding.Convert(Encoding.Unicode, Encoding.GetEncoding(437, new EncoderReplacementFallback(" "), new DecoderReplacementFallback(" ")), src);
    DrawCharacter(g, dest[0]);
}

它将无效字符替换为空格" "

P.S.我最初使用空的string""作为替换,但最后我决定使用空格字符,因为它看起来更干净。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 2010-12-01
    • 2012-01-24
    相关资源
    最近更新 更多