Can we simplify this string encoding code

后端 未结 3 1994
难免孤独
难免孤独 2021-02-08 15:20

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:07

    Does your receipt printer have an API that accepts a byte array rather than a string? If so you may be able to simplify the code to a single conversion, from a Unicode string to a byte array using the encoding used by the receipt printer.

    Also, if you want to convert an array of bytes to a string whose character values correspond 1-1 to the values of the bytes, you can use the code page 28591 aka Latin1 aka ISO-8859-1.

    I.e., the following

    foreach (byte b in converted) 
        builder.Append((char)b); 
    
    string result = builder.ToString(); 
    

    can be replaced by:

    // All three of the following are equivalent
    // string result = Encoding.GetEncoding(28591).GetString(converted);
    // string result = Encoding.GetEncoding("ISO-8859-1").GetString(converted);
    string result = Encoding.GetEncoding("Latin1").GetString(converted);
    

    Latin1 is a useful encoding when you want to encode binary data in a string, e.g. to send through a serial port.

提交回复
热议问题