Can we simplify this string encoding code

后端 未结 3 1997
难免孤独
难免孤独 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:03

    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.

提交回复
热议问题