Sample array & string
byte[] array = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F,
0x57, 0x6F, 0x72, 0x6C, 0x64 }; //"HelloWorld"
String to byte[]
byte[] array= System.Text.Encoding.Default.GetBytes("HelloWorld");
byte[] array= System.Text.Encoding.ASCII.GetBytes("HelloWorld");
String to byte[]
System.Text.ASCIIEncoding converter = new System.Text.ASCIIEncoding();
byte[] array = converter.GetBytes("HelloWorld");
HexString to byte[]
byte[] array = HexToByteArray("48656C6C6F56F726C64");
private static byte[] HexToByteArray(string hexString)
{
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = System.Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
HexString to byte
byte element = HexToByte("48");
private static byte HexToByte(string hexString)
{
if (hexString.Length > 2 || hexString.Length <= 0)
throw new System.ArgumentException("hex must be 1 or 2 characters in length");
byte newByte = byte.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
return newByte;
}
Console array Result
foreach (byte element in array)
{
System.Console.WriteLine("{0}\t{1}\t{2} ",
(char)element, element, element.ToString("X2"));
}
/*
H 72 48
e 101 65
l 108 6C
l 108 6C
o 111 6F
W 87 57
o 111 6F
r 114 72
l 108 6C
d 100 64
*/