TizzyT

ReadHexStringToByte

Jan 4th, 2018
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 0.76 KB | None | 0 0
  1.     Public Function ReadHexStringToByte(ByVal Input As String) As Byte()
  2.         Input = Input.ToUpper().Trim()
  3.         If Input.Length = 0 Then GoTo fail
  4.  
  5.         Dim ValidChar As String = "0123456789ABCDEF"
  6.         For Each character As Char In Input
  7.             If Not ValidChar.Contains(character) Then GoTo fail
  8.         Next
  9.  
  10.         If Input.Length Mod 2 = 1 Then Input = "0" & Input
  11.         Dim ResultBytes As Byte() = New Byte(Input.Length / 2 - 1) {}
  12.         Dim index As Integer = 0
  13.         For i As Integer = 0 To Input.Length - 1 Step 2
  14.             ResultBytes(index) = Convert.ToByte(Input.Substring(i, 2), 16)
  15.             index += 1
  16.         Next
  17.  
  18.         Return ResultBytes
  19. fail:
  20.         Throw New Exception("Invalid HexString")
  21.     End Function
Advertisement
Add Comment
Please, Sign In to add comment