0

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];
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
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Bilgehan
  • 1,135
  • 1
  • 14
  • 41
  • I'm sure there's a duplicate, but I can't find one that quite matches, so I'll answer instead... – Jon Skeet Mar 05 '18 at 08:24
  • What's the purpose of UTF encoding random (probably also invalid) bytes? If you simply want to encode it, use something like Base64 or hex instead. – Manfred Radlwimmer Mar 05 '18 at 08:25
  • The question this was closed as a duplicate of doesn't have a suitable answer for the OP's situation, IMO - it only consists of writing the binary data to a file. Have reopened. (An alternative would be to add an answer to the other question, I guess - there are pros and cons of each approach.) – Jon Skeet Mar 05 '18 at 08:27
  • @JonSkeet well there are 2 answers in that duplicate, and second one talks about using base64 instead of encoding for that. – Evk Mar 05 '18 at 08:32
  • @Evk: Not sure how I'd missed that. It's unfortunate that the whole question is linked with `BitConverter.GetBytes`, but there's not much to be done about that. (Other than possibly creating a canonical question at some point... that might not be a bad idea.) – Jon Skeet Mar 05 '18 at 08:34
  • My scenario is I need a byte[] array ,and its length must be 24 .What I want I want to take a string and convert it to byte array and use it. – Bilgehan Mar 05 '18 at 10:41

0 Answers0