HexToBin and BinToHex

While dealing with storing parts of an X509 certificate, I’ve found the need for a couple of utility methods that allow converting the string representations of the Public Key to a byte array (or vice versa). That’s what the HexToBin() method does. Included also is BinToHex() for going the other direction.

Private Shared Function BinToHex(ByVal data As Byte()) As String
If Not data Is Nothing Then
Dim sb As New System.Text.StringBuilder
For i As Integer
= 0 To data.Length - 1

Return sb.ToString()
Return Nothing
End If
End Function

Public Shared Function HexToBin(ByVal s As String) As Byte()
Dim arraySize As Integer
= CInt(s.Length / 2)
Dim bytes(arraySize
- 1) As Byte
Dim counter As Integer

For i As Integer
= 0 To s.Length - 1 Step 2
Dim hexValue As String
= s.Substring(i, 2)

' Tell convert to interpret the string as a 16 bit hex value
Dim intValue As Integer = Convert.ToInt32(hexValue, 16)
' Convert the integer to a byte and store it in the array
bytes(counter) = Convert.ToByte(intValue)
+= 1

Return bytes
End Function

If you found this article helpful:


  1. Oh yea - a null check on the passed in string argument would be wise in the HexToBin(s) method.

  2. Hah - naw, I code in whatever the client dictates. :D VB.NET, C#, RPG.NET. It's all the same. :) My preferences is still C#.