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; rnd.NextBytes(bytes); 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
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:
See more on this question at Stackoverflow