C#: Converting byte array to string and printing out to console
It's actually:
Console.WriteLine(Encoding.Default.GetString(value));
or for UTF-8 specifically:
Console.WriteLine(Encoding.UTF8.GetString(value));
I was in a predicament where I had a signed byte array (sbyte[]
) as input to a Test class and I wanted to replace it with a normal byte array (byte[]
) for simplicity. I arrived here from a Google search but Tom's answer wasn't useful to me.
I wrote a helper method to print out the initializer of a given byte[]
:
public void PrintByteArray(byte[] bytes)
{
var sb = new StringBuilder("new byte[] { ");
foreach (var b in bytes)
{
sb.Append(b + ", ");
}
sb.Append("}");
Console.WriteLine(sb.ToString());
}
You can use it like this:
var signedBytes = new sbyte[] { 1, 2, 3, -1, -2, -3, 127, -128, 0, };
var unsignedBytes = UnsignedBytesFromSignedBytes(signedBytes);
PrintByteArray(unsignedBytes);
// output:
// new byte[] { 1, 2, 3, 255, 254, 253, 127, 128, 0, }
The ouput is valid C# which can then just be copied into your code.
And just for completeness, here is the UnsignedBytesFromSignedBytes
method:
// http://stackoverflow.com/a/829994/346561
public static byte[] UnsignedBytesFromSignedBytes(sbyte[] signed)
{
var unsigned = new byte[signed.Length];
Buffer.BlockCopy(signed, 0, unsigned, 0, signed.Length);
return unsigned;
}
I've used this simple code in my codebase:
static public string ToReadableByteArray(byte[] bytes)
{
return string.Join(", ", bytes);
}
To use:
Console.WriteLine(ToReadableByteArray(bytes));