If you need to convert a string into a byte array in VB.NET, you can use the GetBytes method of one of the encoding objects available in the System.Text namespace. This tip shows various encoding types and looks at ways to convert a string into a byte array.
There are a number of ways to represent a string variable in a binary form. The encoding object you utilize to achieve this functionality depends on the encoding you selected.
Here are the encoding types that developers use most often:
- ASCII: Encodes each character in a string using seven bits. This encoding type cannot contain extended Unicode characters.
- Full Unicode (UTF-16): Represents each character in a string using 16 bits. This results in a byte array that has two bytes for each character.
- UTF-7: Uses seven bits for ordinary ASCII characters and multiple seven-bit pairs for extended characters. This encoding type is most often used with seven-bit protocols, such as mail.
- UTF-8: Uses eight bits for ordinary ASCII characters and multiple eight-bit pairs for extended characters. This results in a byte array that has one byte for each character (assuming there are no extended characters).
Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.
————————————————————————————————————————————Get Visual Basic tips in your inbox
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!