Hex ASCII String to Byte Array

By Steven Chang

December 16, 2010

hex ascii to byte array, hex string to byte, hex string to byte array, hex to byte, hex to byte array

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)
Next
Return bytes
End Function[/code]

Validation:
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.

Steven Chang

About the author

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Direct Your Visitors to a Clear Action at the Bottom of the Page

>