Performance loss in VB.net equivalent of light weight conversion from hex to byte

梦想与她 提交于 2019-12-13 21:41:52

问题


I have read through the answers here https://stackoverflow.com/a/14332574/44080

I've also tried to produce equivalent VB.net code:

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

Can we remove the compile errors in ParseNybble without introducing data conversions?

Return c - "0"c Operator '-' is not defined for types 'Char' and 'Char'

c = ChrW(c And Not &H20) Operator 'And' is not defined for types 'Char' and 'Integer'


回答1:


As it stands, no.

However, you could change ParseNybble to take an integer and pass AscW(hexString.Chars(j)) to it, so that the data conversion takes place outside of ParseNybble.




回答2:


This solution is much much faster than all the alternative i have tried. And it avoids any ParseNybble lookup.

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


来源:https://stackoverflow.com/questions/32074624/performance-loss-in-vb-net-equivalent-of-light-weight-conversion-from-hex-to-byt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!