Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I safely convert a byte array into a string and back? [duplicate]

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?

like image 807
Svish Avatar asked Jul 15 '09 23:07

Svish


People also ask

How does Java convert byte array to string?

Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .

Can we convert byte to string in Java?

Given a Byte value in Java, the task is to convert this byte value to string type. One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.


2 Answers

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.

like image 179
Jon Skeet Avatar answered Oct 08 '22 09:10

Jon Skeet


You can just use the Convert class as below.

/// <summary> /// Converts a string to byte array /// </summary> /// <param name="input">The string</param> /// <returns>The byte array</returns> public static byte[] ConvertToByteArray(string input) {     return input.Select(Convert.ToByte).ToArray(); }  /// <summary> /// Converts a byte array to a string /// </summary> /// <param name="bytes">the byte array</param> /// <returns>The string</returns> public static string ConvertToString(byte[] bytes) {     return new string(bytes.Select(Convert.ToChar).ToArray()); }  /// <summary> /// Converts a byte array to a string /// </summary> /// <param name="bytes">the byte array</param> /// <returns>The string</returns> public static string ConvertToBase64String(byte[] bytes) {     return Convert.ToBase64String(bytes); } 
like image 35
Ricky Gummadi Avatar answered Oct 08 '22 07:10

Ricky Gummadi