Problem
I have a byte[] array loaded from a file that includes UTF-8, as far as I know.
I need to convert it to a string in some debugging code. Is there a one-liner that’ll suffice?
It should just be an allocation and a memcopy behind the hood, so even if it isn’t implemented, it should be doable.
Asked by BCS
Solution #1
string result = System.Text.Encoding.UTF8.GetString(byteArray);
Answered by Zanoni
Solution #2
There’re at least four different ways doing this conversion.
A full example:
byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters
string s1 = Encoding.UTF8.GetString(bytes); // ���
byte[] decBytes1 = Encoding.UTF8.GetBytes(s1); // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results
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);
// decBytes2 same as bytes
string s3 = Convert.ToBase64String(bytes); // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes
string s4 = HttpServerUtility.UrlTokenEncode(bytes); // gsjqFw2
byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4);
// decBytes4 same as bytes
Answered by detale
Solution #3
When you don’t know the encoding, here’s a general technique for converting from byte array to string:
static string BytesToStringConverted(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
Answered by Nir
Solution #4
Definition:
public static string ConvertByteToString(this byte[] source)
{
return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}
Using:
string result = input.ConvertByteToString();
Answered by Erçin Dedeoğlu
Solution #5
Converting a byte[] to a string appears straightforward, but any encoding is likely to cause problems with the resulting string. This small function just works, with no unexpected outcomes:
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}
Answered by AndrewJE
Post is based on https://stackoverflow.com/questions/1003275/how-to-convert-utf-8-byte-to-string