Can we simplify this string encoding code

后端 未结 3 584
刺人心
刺人心 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 15:58

    Almost anything would be cleaner than this - you're really abusing text here, IMO. You're trying to represent effectively opaque binary data (the encoded text) as text data... so you'll potentially get things like bell characters, escapes etc.

    The normal way of encoding opaque binary data in text is base64, so you could use:

    return Convert.ToBase64String(Encoding.GetEncoding(936).GetBytes(text));
    

    The resulting text will be entirely ASCII, which is much less likely to cause you hassle.

    EDIT: If you need that output, I would strongly recommend that you represent it as a byte array instead of as a string... pass it around as a byte array from that point onwards, so you're not tempted to perform string operations on it.

提交回复
热议问题