Since you're using the BitConverter
, the string you get is specifically formatted in a less than friendly way. To reverse this process, you can write a custom method to deserialize the bytes like this:
public static byte[] GetBytes(string value)
{
return value.Split('-').Select(s => byte.Parse(s, System.Globalization.NumberStyles.HexNumber)).ToArray();
}
Or as Ben Voigt suggests:
public static byte[] GetBytes(string value)
{
return Array.ConvertAll(value.Split('-'), s => byte.Parse(s, System.Globalization.NumberStyles.HexNumber));
}
...
var originalBytes = new byte[] { 1, 2, 3, 4, 5 };
var stValue = BitConverter.ToString(originalBytes); // "01-02-03-04-05"
var bytes = GetBytes(stValue); // [ 1, 2, 3, 4, 5 ]
However, usually don't need to use the BitConverter
. Base64 is a more compact and efficient way of encoding random bytes, and you won't have to create a custom decoder:
var originalBytes = new byte[] { 1, 2, 3, 4, 5 };
var stValue = Convert.ToBase64String(originalBytes); // "AQIDBAU="
var bytes = Convert.FromBase64String(stValue); // [ 1, 2, 3, 4, 5 ]
On the other hand, the Encoding
class offers similar functionality for converting between strings and bytes. Although a given encoding may not be able to translate a random sequence of bytes into a string so it's best to use this method only if you know the string is valid first:
var originalValue = "Hello World";
var bytes = Encoding.UTF8.GetBytes(originalValue); // [ 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 ]
var stValue = Encoding.UTF8.GetString(bytes); // "Hello World"