Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte[] to String to Byte[] -- How to do so?

Ignore the reasons why someone would want to do this.... :)

I want to be able to take some bytes, covert them to a string, then later back to the same byte array. Same length and everything.

I've tried using the ASCIIEncoder class (works for only text files) and Unicode Encoder class (only works so far for arrays 1024*n big. I assume this is because of the equal length of each character) with no success.

Is there any easy way to do this? I assume I should probably write my own functions to do so huh?

like image 942
bobber205 Avatar asked Dec 11 '25 04:12

bobber205


2 Answers

Use Base64 encoding. It's not space-efficient though.

string s = Convert.ToBase64String(byteArray);
byte[] decoded = Convert.FromBase64String(s);
like image 168
mmx Avatar answered Dec 12 '25 17:12

mmx


Base64 is great at problems like this.

string str = Convert.ToBase64String(inArray);
...
byte[] ourArray = Convert.FromBase64String(str);

Note that the resulting string will be larger (of course) than your original array.

like image 22
Michael Petrotta Avatar answered Dec 12 '25 18:12

Michael Petrotta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!