-1

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.UrlTokenDecodethe 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.

None
  • 609
  • 7
  • 22
  • If you want the one that uses the lest amount of data [`Convert.ToBase64String`](https://msdn.microsoft.com/en-us/library/system.convert.tobase64string(v=vs.110).aspx) will give you a much shorter string than all of the items you listed above. – Scott Chamberlain Jul 19 '16 at 19:49
  • 2
    Also, what does the question "[How do you convert Byte Array to Hexadecimal String, and vice versa?](http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa)" not cover for you? – Scott Chamberlain Jul 19 '16 at 19:50

1 Answers1

1

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.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431