How do I convert a byte[]
to a string
? Every time I attempt it, I get
System.Byte[]
instead of the value.
Also, how do I get the value in decimal instead of hexadecimal?
using the below code I'm getting in hexadecimal only
string hex = BitConverter.ToString(data);
here is my code
static void Main(string[] args)
{
Program obj = new Program();
byte[] byteData;
int n;
byteData = GetBytesFromHexString("001C0014500C0A5B06A4FFFFFFFFFFFFFFFFFFFFFFFFFFFF");
n = byteData.Length;
string s = BitConverter.ToString(byteData);
Console.WriteLine("<Command Value='" + s + "'/>");
Console.WriteLine("</AudioVideo>");
Console.ReadLine();
}
public static byte[] GetBytesFromHexString(string hexString)
{
if (hexString == null)
return null;
if (hexString.Length % 2 == 1)
hexString = '0' + hexString; // Up to you whether to pad the first or last byte
byte[] data = new byte[hexString.Length / 2];
for (int i = 0; i < data.Length; i++)
data[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
Console.WriteLine(data);
return data;
}
output should be:
0 28 0 20 80 12 10 91 6 164 255 255 255 255 255 255 255 255 255 255 255 255 255 255
output should be stored in a string and displayed.
Replace the line
string s = BitConverter.ToString(byteData);
with
string s = string.Join(" ", byteData.Select(b => b.ToString()));
and you should be good to go.