代码之家  ›  专栏  ›  技术社区  ›  AndiDog

C语言中严格的字符串到字节编码#

  •  3
  • AndiDog  · 技术社区  · 14 年前

    我只是被绊倒了 another question 其中有人建议使用 new ASCIIEncoding().GetBytes(someString) 从字符串转换成字节。对我来说,它显然不应该适用于非ASCII字符。但事实证明, ASCIIEncoding 用“?”替换无效字符。我对此很困惑,因为这打破了最小惊喜的规则。在Python中 u"some unicode string".encode("ascii")

    两个问题:

    1. 关于这种默认行为背后的基本原理有什么想法吗?对我来说,在默认情况下进行严格转换或者至少为此定义一个参数更有意义(Python允许“replace”、“ignore”、“strict”)。
    1 回复  |  直到 8 年前
        1
  •  8
  •   Michael Petrotta user3140870    14 年前

    Net提供了在编码转换失败时引发异常的选项。你需要使用 EncoderExceptionFallback

    Encoding ae = Encoding.GetEncoding(
                  "us-ascii",
                  new EncoderExceptionFallback(), 
                  new DecoderExceptionFallback());
    

    然后使用该编码执行转换:

    // The input string consists of the Unicode characters LEFT POINTING 
    // DOUBLE ANGLE QUOTATION MARK (U+00AB), 'X' (U+0058), and RIGHT POINTING 
    // DOUBLE ANGLE QUOTATION MARK (U+00BB). 
    // The encoding can only encode characters in the US-ASCII range of U+0000 
    // through U+007F. Consequently, the characters bracketing the 'X' character
    // cause an exception.
    
    string inputString = "\u00abX\u00bb";
    byte[] encodedBytes = new byte[ae.GetMaxByteCount(inputString.Length)];
    int numberOfEncodedBytes = 0;
    try
    {
        numberOfEncodedBytes = ae.GetBytes(inputString, 0, inputString.Length, 
                                           encodedBytes, 0);
    }
    catch (EncoderFallbackException e)
    {
        Console.WriteLine("bad conversion");
    }
    

    这个 MSDN page, "Character Encoding in the .NET Framework"