Public Shared Function StringToByteArrayFastest(hex As String) As Byte()
If hex.Length Mod 2 = 1 Then
Throw New Exception("The binary key cannot have an odd number of digits")
End If
Dim arr As New Byte((hex.Length >> 1) - 1)
For i As Integer = 0 To (hex.Length >> 1) - 1
arr(i) = CByte((GetHexVal(hex(i << 1)) << 4) + (GetHexVal(hex((i << 1) + 1))))
Next
Return arr
End Function
Public Shared Function GetHexVal(hex As Char) As Integer
Dim val As Integer = AscW(hex)
'For uppercase A-F letters:
Return val - (If(val < 58, 48, 55))
'For lowercase a-f letters:
'return val - (val < 58 ? 48 : 87);
'Or the two combined, but a bit slower:
'return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
End Function
Možné řešení z http://stackoverflow.com/a/9995303, pravděpodobně také dostatečně výkonné.
|