How to convert a String to byte Array and back

To convert a String to byte Array and back you can use the following snippet.

Sample C#

public static byte[] GetBytes(string input)
{
    var byteArray = new byte[input.Length * sizeof(char)];
    Buffer.BlockCopy(input.ToCharArray(), 0, byteArray, 0, byteArray.Length);
    return byteArray;
}

public static string GetString(byte[] byteArray)
{
    var characters = new char[byteArray.Length / sizeof(char)];
    Buffer.BlockCopy(byteArray, 0, characters, 0, byteArray.Length);
    return new string(characters);
}

Sample VB.NET

Public Shared Function GetBytes(input As String) As Byte()
    Dim byteArray = New Byte(input.Length * 2 - 1) {}
    Buffer.BlockCopy(input.ToCharArray(), 0, byteArray, 0, byteArray.Length)
    Return byteArray
End Function

Public Shared Function GetString(byteArray As Byte()) As String
    Dim characters = New Char(byteArray.Length / 2 - 1) {}
    Buffer.BlockCopy(byteArray, 0, characters, 0, byteArray.Length)
    Return New String(characters)
End Function

One thought on “How to convert a String to byte Array and back

Leave a Reply