.NET C# byte[] to String sample

Sample array & string

byte[] array = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F, 
0x57, 0x6F, 0x72, 0x6C, 0x64 }; //"HelloWorld"

byte[] to String

string str = System.Text.Encoding.Default.GetString(array);
string str = System.Text.Encoding.ASCII.GetString(array);

byte[] to String

System.Text.ASCIIEncoding converter = new System.Text.ASCIIEncoding();
string str = converter.GetString(array);

HexString to byte[]

string str = ByteArrayToHex(array);
public static string ByteArrayToHex(byte[] array)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (byte element in array)
sb.Append(element.ToString("X2"));
return sb.ToString();
}

.NET C# String to byte[] sample

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
*/