Thursday, August 26, 2010

Some Useful Functions


Sometimes you may want to convert a string into a byte array, or vice versa, especially when you are using the Cryptographic APIs. I have provided three functions here to help you make the conversions. The three functions are:

stringcharToByteArray(): converts a string of characters to a byte array.
stringToByteArray(): converts a string of numbers into a byte array.
byteArrayToString(): converts a byte array into a string.

    Public Function stringcharToByteArray(ByVal str As String) As Byte()
        'e.g. "abcdefg" to {a,b,c,d,e,f,g}
        Dim s As Char()
        s = str.ToCharArray
        Dim b(s.Length - 1) As Byte
        Dim i As Integer
        For i = 0 To s.Length - 1
            b(i) = Convert.ToByte(s(i))
        Next
        Return b
    End Function
 
    Public Function stringToByteArray(ByVal str As String) As Byte()
        ' e.g. "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16" to 
        '{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
        Dim s As String()
        s = str.Split(" ")
        Dim b(s.Length - 1) As Byte
        Dim i As Integer
        For i = 0 To s.Length - 1
            b(i) = Convert.ToByte(s(i))
        Next
        Return b
    End Function
 
    Public Function byteArrayToString(ByVal b() As Byte) As String
        Dim i As Integer
        Dim s As New System.Text.StringBuilder()
        For i = 0 To b.Length - 1
            Console.WriteLine(b(i))
            If i <> b.Length - 1 Then
                s.Append(b(i) & " ")
            Else
                s.Append(b(i))
            End If
        Next
        Return s.ToString
    End Function

No comments:

Post a Comment