ByteArray to string then string to byte array

I have a custom byte array and it's length 24byte ,I try to transform to string and back again but my result is different.What is the best way to do this.

var z = Guid.NewGuid().ToByteArray();
Random rnd = new Random();
byte[] bytes = new byte[8];
byte[] rv = z.Concat(bytes).ToArray();
string converted = Encoding.UTF8.GetString(rv, 0, rv.Length);//converted string is completely different I cant see my GuidId in this
byte[] rx = Encoding.UTF8.GetBytes(converted);//Transforming code is 44 byte
Jon Skeet

You shouldn't use Encoding.GetString to convert arbitrary binary data into a string. That method is only intended for text that has been encoded to binary data using a specific encoding.

Instead, you want to use a text representation which is capable of representing arbitrary binary data reversibly. The two most common ways of doing that are base64 and hex. Base64 is the simplest in .NET:

string base64 = Convert.ToBase64String(rv);
byte[] rx = Convert.FromBase64String(base64);

A few caveats to this:

  • If you want to use this string as a URL parameter, you should use a web-safe version of base64; I don't know of direct support for that in .NET, but you can probably find solutions easily enough
  • You should only do this at all if you really need the data in string format. If you're just trying to write it to a file or similar, it's simplest to keep it as binary data
  • Base64 isn't very human-readable; use hex if you want humans to be able to read the data in its text form without extra tooling. (There are various questions specifically about converting binary data to hex and back.)


See more on this question at Stackoverflow