How to Convert Byte Array to String in C#

In .NET, a byte is just a number from 0 to 255 (the numbers that can be represented by eight bits). So, a byte array is just an array of the numbers from 0 to255. At a lower level, an array is a contiguous block of memory, and a byte array is just a representation of that memory in 8-bit blocks.

Let's say you have a Byte[] array loaded from a file and you need to convert it to a String.

1. Encoding's GetString
but you won't be able to get the original bytes back if those bytes have non-ASCII characters

byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters
string Enco = Encoding.UTF8.GetString(bytes); 
byte[] decBytes1 = Encoding.UTF8.GetBytes(Enco);  // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results

2. BitConverter.ToString
The output is a "-" delimited string, but there's no .NET built-in method to convert the string back   to byte array.

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

3. Convert.ToBase64String
You can easily convert the output string back to byte array by using Convert.FromBase64String.
Note: The output string could contain '+', '/' and '='. If you want to use the string in a URL, you need to explicitly encode it.

string B64 = Convert.ToBase64String(bytes);  
byte[] decByte3 = Convert.FromBase64String(B64);
// decByte3 same as bytes

4. HttpServerUtility.UrlTokenEncode
You can easily convert the output string back to byte array by using HttpServerUtility.UrlTokenDecode. The output string is already URL friendly! The downside is it needs System.Web assembly if your project is not a web project.

string s3 = Convert.ToBase64String(bytes);  // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes

Credits : combo_ci

Post a Comment