None None - 3 months ago 18
C# Question

Best way of converting between byte[] and string?

I know this question was asked two times before on stack-overflow, but this time I'm asking for the most guaranteed way of doing so(The way that doesn't change the value of the data). I want to convert from string to byte[] then back to string. I could use

ByteConverter
,
Convert
,
Encoding
,
BitConverter
,
HttpServerUtility.UrlTokenEncode / HttpServerUtility.UrlTokenDecode
the following code:

string s2 = BitConverter.ToString(bytes); // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
{
decBytes2[i] = Convert.ToByte(tempAry[i], 16);
}


or the following code:

private string ToString(byte[] bytes)
{
string response = string.Empty;

foreach (byte b in bytes)
response += (Char)b;

return response;
}


If you don't still get what I want, I wanna know which way works and which doesn't, I wanna know which way is should be used. Hey, I would prefer a byte array with with the least size because I'll be sending this array over the network, and I'll use the first 256 bytes.

Answer

I want to convert from string to byte[] then back to string.

If that is what you are actually trying to do all you need to do is just use Encoding.UTF8.GetBytes(string) on the sending side and Encoding.UTF8.GetString(byte[]) on the receiving side.

private byte[] ToBytes(string message)
{
    return Encoding.UTF8.GetBytes(message);
}

private string ToString(byte[] bytes)
{
    return Encoding.UTF8.GetString(bytes);
}

This will give you a round trip to convert any string to bytes and back to a string again in the fewest number of bytes.

This will NOT work to do byte[] to string to byte[], for somthing like that you need to use something like Convert.ToBase64String(byte[]) and Convert.FromBase64String(string). Using Encoding.UTF8.GetString(byte[]) on something that was not a properly formatted UTF8 string will potentially cause you to loose data in the conversion.

Comments