I have a byte[]
array that is loaded from a file that I happen to known contains UTF-8.
In some debugging code, I need to convert it to a string. Is
BitConverter
class can be used to convert a byte[]
to string
.
var convertedString = BitConverter.ToString(byteAttay);
Documentation of BitConverter
class can be fount on MSDN
hier is a result where you didnt have to bother with encoding. I used it in my network class and send binary objects as string with it.
public static byte[] String2ByteArray(string str)
{
char[] chars = str.ToArray();
byte[] bytes = new byte[chars.Length * 2];
for (int i = 0; i < chars.Length; i++)
Array.Copy(BitConverter.GetBytes(chars[i]), 0, bytes, i * 2, 2);
return bytes;
}
public static string ByteArray2String(byte[] bytes)
{
char[] chars = new char[bytes.Length / 2];
for (int i = 0; i < chars.Length; i++)
chars[i] = BitConverter.ToChar(bytes, i * 2);
return new string(chars);
}
Converting a byte[]
to a string
seems simple but any kind of encoding is likely to mess up the output string. This little function just works without any unexpected results:
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}
string result = System.Text.Encoding.UTF8.GetString(byteArray);
A Linq one-liner for converting a byte array byteArrFilename
read from a file to a pure ascii C-style zero-terminated string would be this: Handy for reading things like file index tables in old archive formats.
String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
.Select(x => x < 128 ? (Char)x : '?').ToArray());
I use '?'
as default char for anything not pure ascii here, but that can be changed, of course. If you want to be sure you can detect it, just use '\0'
instead, since the TakeWhile
at the start ensures that a string built this way cannot possibly contain '\0'
values from the input source.
Definition:
public static string ConvertByteToString(this byte[] source)
{
return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}
Using:
string result = input.ConvertByteToString();