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

时间:2015-08-18 14:02:28

标签: vb.net hex bytearray

我在这里阅读了答案https://stackoverflow.com/a/14332574/44080

我还试图生成等效的VB.net代码:

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

我们可以在不引入数据转换的情况下删除ParseNybble中的编译错误吗?

Return c - "0"c 运营商&#39; - &#39;未定义类型&#39; Char&#39;和&#39; Char&#39;

c = ChrW(c And Not &H20) 运营商&#39;以及&#39;未定义类型&#39; Char&#39;和&#39;整数&#39;

2 个答案:

答案 0 :(得分:1)

现在,没有。

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

答案 1 :(得分:0)

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

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