Converting Strings To Bytes and Vice Versa
Converting Strings To Bytes and Vice Versa
Use these functions to convert a string of text to an unambiguous array of bytes and vice
versa.
VB6 stores its strings internally in "Unicode" format, two bytes per character, but the
StrConv function will convert to an array of bytes encoded in "ANSI" format using your
default code page.
In .NET strings are stored internally in "Unicode" format (UTF-16) and the GetBytes
method can extract an array of bytes in any encoding you want.
The .Default encoding uses the default code page on your system which is usually
1252 (Western European) but may be different on your setup. If you want ISO-8859-1
(Latin-1) you can replace .Default with .GetEncoding(28591) (code page 28591 is
ISO-8859-1 which is identical to Windows-1252 except for characters in the range 0x80
to 0x9F). Alternatively use System.Text.Encoding.GetEncoding("iso-8859-
1").GetBytes(Str). If you want UTF-8-encoded bytes, use
System.Text.Encoding.UTF8.GetBytes(Str).
byte[] abData;
string Str;
int i;
Str = "Hello world!";
// Convert string to bytes
abData = System.Text.Encoding.Default.GetBytes(Str);
for (i = 0; i < abData.Length; i++)
{
Console.WriteLine("{0:X}", abData[i]);
}
// Convert bytes to string
Str = System.Text.Encoding.Default.GetString(abData);
Console.WriteLine("'{0}'", Str);