Friday, 2 June 2017

c# - How can I safely convert a byte array into a string and back?




I don't really care about encoding and stuff, as long as I get back the exact same byte array.




So to sum up: How do I convert a byte array into a string, and then that string back into the same byte array I started with?


Answer



The absolute safest way to convert bytes to a string and back is to use base64:



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


That way you're guaranteed not to get "invalid" unicode sequences such as the first half of a surrogate pair without the second half. Nothing's going to decide to normalize the data into something strange (it's all ASCII). There's no chance of using code points which aren't registered in Unicode, or anything like that. Oh, and you can cut and paste without much fear, too.




Yes, you end up with 4 characters for every 3 bytes - but that's a small price to pay for the knowledge that your data won't be corrupted.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...