VB.net中的性能损失相当于从十六进制到字节的轻量级转换

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'定义Return c -"0"c运算符'-'

没有为类型'char'和'integer'定义c = ChrW(c And Not &H20)运算符'and'


事实上,没有。

但是,您可以将ParseNybble更改为取整数,并将AscW(hexString.Chars(j))传递给它,以便在parsenybble之外进行数据转换。


这个解决方案比我尝试过的所有替代方案都快得多。它避免了任何ParseNybble查找。

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