.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();
}

沒有留言:

張貼留言