Code Snippets VB.Net

VB.Net - Convert String Buffer to Byte Array.

IncludeHelp VB.Net 14 OCT 2016


In this VB.Net code we will learn how to convert a string buffer into Byte Array?

In this example there is a form with textbox and button control, string will be entered into textbox and converted byte array’s values will be printed in message box on button click event.

For example there is a string buffer "ABCD" it will be converted into "65666768" which are the byte (integer) values of given characters in the string.

To convert string buffer to byte array - we are using System.Text.Encoding.Unicode.GetBytes(strBuffer) which will return byte array.

VB.Net Code – Convert String Buffer to Byte Array

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim strBuffer As String = Nothing

        strBuffer = TextBox1.Text.Trim

        'declare byte buffer based on strBuffer length

        Dim byteArray(strBuffer.Length()) As Byte

        byteArray = System.Text.Encoding.Unicode.GetBytes(strBuffer)

        'printing byte array in string
        Dim finalString As String = Nothing

        'why step 2 - in byteArray each character will take 2 bytes, 
        ' for example Byte value of A is: 65 0
        ' and we have to pick 65 only 
        For counter As Integer = 0 To byteArray.Length - 1 Step 2
            finalString = finalString & byteArray(counter).ToString(0) & " "
        Next

        MsgBox("Byte Array values are: " & finalString)

    End Sub
End Class

Output

convert string buffer to byte array in vb.net




Copyright © 2024 www.includehelp.com. All rights reserved.