Performance loss in VB.net equivalent of light weight conversion from hex to byte
我已经阅读了这里的答案https://stackoverflow.com/a/14332574/44080
我还尝试生成等效的vb.net代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | Option Strict ON Public Function ParseHex(hexString As String) As Byte() If (hexString.Length And 1) <> 0 Then Throw New ArgumentException("Input must have even number of characters") End If Dim length As Integer = hexString.Length \ 2 Dim ret(length - 1) As Byte Dim i As Integer = 0 Dim j As Integer = 0 Do While i < length Dim high As Integer = ParseNybble(hexString.Chars(j)) j += 1 Dim low As Integer = ParseNybble(hexString.Chars(j)) j += 1 ret(i) = CByte((high << 4) Or low) i += 1 Loop Return ret End Function Private Function ParseNybble(c As Char) As Integer If c >="0"C AndAlso c <="9"C Then Return c -"0"C End If c = ChrW(c And Not &H20) If c >="A"C AndAlso c <="F"C Then Return c - ("A"C - 10) End If Throw New ArgumentException("Invalid nybble:" & c) End Function |
我们能在不引入数据转换的情况下删除parsnybble中的编译错误吗?
没有为类型'char'和'char'定义
没有为类型'char'和'integer'定义
事实上,没有。
但是,您可以将
这个解决方案比我尝试过的所有替代方案都快得多。它避免了任何
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Function hex2byte(s As String) As Byte() Dim l = s.Length \ 2 Dim hi, lo As Integer Dim b(l - 1) As Byte For i = 0 To l - 1 hi = AscW(s(i + i)) lo = AscW(s(i + i + 1)) hi = (hi And 15) + ((hi And 64) >> 6) * 9 lo = (lo And 15) + ((lo And 64) >> 6) * 9 b(i) = CByte((hi << 4) Or lo) Next Return b End Function |