Search code examples
c#encodingnon-printable

Conversion of strings containing non printable characters


I would like to convert a byte array containing non printable characters to string for my application. When I convert back to byte array, the contents of the array should remain the same as I found that ASCII/Unicode/UTF8 doesnt always give me the right solution?

E.g

 byte[] bytearray ={ 147, 35, 44, 18, 255, 104, 206, 72 ,69};

 string str = System.Text.Encoding.ASCII.GetString(bytearray);

 bytearray = System.Text.Encoding.ASCII.GetBytes(str);

In the above example, I find that the byte array contains

{ 63, 35, 44, 18, 63, 104, 63, 72 ,69}.

Kindly help me.


Solution

  • Take a look at Convert.ToBase64String method. It will convert a byte array into string. Have in mind that encoded into string that data will take up more space than your original byte array would.

    public static string ToBase64String(
        byte[] inArray
    )
    

    You can then decode string back to byte array using FromBase64String

    public static byte[] FromBase64String(
        string s
    )