Can we simplify this string encoding code

后端 未结 3 585
刺人心
刺人心 2021-02-08 15:15

Is it possible to simplify this code into a cleaner/faster form?

StringBuilder builder = new StringBuilder();
var encoding = Encoding.GetEncoding(936);

// conv         


        
3条回答
  •  醉梦人生
    2021-02-08 16:00

    Well, for one, you don't need to convert the "built-in" string representation to a byte array before calling Encoding.Convert.

    You could just do:

    byte[] converted = Encoding.GetEncoding(936).GetBytes(text);
    

    To then reconstruct a string from that byte array whereby the char values directly map to the bytes, you could do...

    static string MangleTextForReceiptPrinter(string text) {
        return new string(
            Encoding.GetEncoding(936)
                .GetBytes(text)
                .Select(b => (char) b)
                .ToArray());
    }
    

    I wouldn't worry too much about efficiency; how many MB/sec are you going to print on a receipt printer anyhow?

    Joe pointed out that there's an encoding that directly maps byte values 0-255 to code points, and it's age-old Latin1, which allows us to shorten the function to...

    return Encoding.GetEncoding("Latin1").GetString(
               Encoding.GetEncoding(936).GetBytes(text)
           );
    

    By the way, if this is a buggy windows-only API (which it is, by the looks of it), you might be dealing with codepage 1252 instead (which is almost identical). You might try reflector to see what it's doing with your System.String before it sends it over the wire.

提交回复
热议问题