O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Convert a String into a Byte Array

Problem

You need to convert a string into a series of bytes, possibly before writing it to a stream or applying encryption.

Solution

Call the GetBytes method on one of the encoding objects from the System.Text namespace.

Discussion

There is more than one way to represent a string in binary form, depending on the encoding you use. The most common encodings include:

  • ASCII. Encodes each character in a string using 7 bits. ASCII encoded data can’t contain extended Unicode characters. When using ASCII encoding in .NET, the bits will be padded and the resulting byte array will have one byte for each character.

  • Full Unicode (or UTF-16). Represents each character in a string using 16 bits. The resulting byte array will have ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required