Home
VB.NET
Convert String, Byte Array
Updated Sep 27, 2021
Dot Net Perls
Convert String, Byte Array. In VB.NET, a String can be stored as a series of Bytes. This is an efficient encoding for ASCII-only Strings.
Conversion notes. This conversion can make file formats more efficient, and it can help compatibility. In VB.NET we can convert Strings to Byte arrays.
Byte, Sbyte
Array
Example. The ASCII.GetBytes() Function receives an argument of String type. And it returns a Byte array reference. We do not need to allocate the Byte array—this is automatically done.
Byte Array
Detail The 6 characters are converted into bytes. In a program, these 6 bytes could be written to a binary file, as with BinaryWriter.
Char
BinaryWriter
Warning If you try to write non-ASCII characters, this will cause serious trouble. Data will be lost or even corrupted.
Module Module1 Sub Main() ' The input String. Dim value As String = "abc!" ' Convert String to Byte array. Dim array() As Byte = System.Text.Encoding.ASCII.GetBytes(value) ' Display Bytes. For Each b As Byte In array Console.WriteLine("{0} = {1}", b, ChrW(b)) Next End Sub End Module
97 = a 98 = b 99 = c 33 = !
Example 2. We can convert Bytes into Strings—for this we use the ASCII.GetString() Function. This Function receives a Byte array and it returns the converted String.
Detail We see that the output of this program is same as the previous program. ASCII.GetString round-trips the bytes from ASCII.GetBytes.
Module Module1 Sub Main() ' Input Bytes. Dim array() As Byte = {86, 66, 46, 78, 69, 84} ' Use GetString. Dim value As String = System.Text.ASCIIEncoding.ASCII.GetString(array) Console.WriteLine(value) End Sub End Module
VB.NET
Notes, char functions. Other Functions, such as ASCII.GetChars, are also available. We can get char arrays, or counts of chars, from these functions. These are less often needed in my experience.
Detail This returns a Char array containing the characters represented by the individual Bytes.
String Constructor
Detail This Function returns the number of characters in the output Char array.
A summary. Having an efficient way to store character data is important. Sometimes this is useful for compatibility—a function may require bytes, but we have a string.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 27, 2021 (new example).
Home
Changes
© 2007-2025 Sam Allen