Hex ASCII String to Byte Array

Written By Steven Chang  |  VB.NET  |  0 Comments

Here is a function that takes in a string of Hex and converts to byte array.

For example:

[code]Dim bytes = HexStringToBytes(“ABCD”)[/code]

bytes will now contain 2 elements, first with value of 0xAB (or 171 decimal) and second with value of 0xCD (or 205 decimal):

Here is the function:

[code] ‘convert hex string to byte array (taking 2 chars at a time)
Public Function HexStringToBytes(ByVal hex As String) As Byte()
Dim NumChars As Integer = hex.Length
Dim bytes((NumChars / 2) – 1) As Byte
Dim index As Integer
For index = 0 To NumChars – 1 Step 2
bytes(Math.Floor(index / 2)) = Convert.ToByte(hex.Substring(index, 2), 16)
Return bytes
End Function[/code]

It’s probably a good idea that you implement your own validation that the input needs to be multiples of 2, otherwise an exception will occur.

About the Author

The roles I play: Husband, Dad, Son, Brother, Friend, Programmer, Investor, Trader, Marketer, Student, Teacher, Leader, Follower, Influencer