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 ...
Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.