VB Hex Function used for Bit Decoding in Excel

Attribute VB_Name = "HexFunctions"
' Returns the a bit range in a given hex
Function Bits(HexNum As String, startBit As Integer, endBit As Integer) As String
    Dim num, mask, startDivider, Results As Long

    num = CLng("&H" & HexNum)
    mask = 0

    ' play this silly trick to avoid overflows when doing things with 2^31
    If endBit = 31 Then
        endBit = 30
        OrVal = &H80000000
    Else
        OrVal = 0
    End If

    'create the mask 1s
    For i = startBit To endBit
        mask = mask Or (2 ^ i)
    Next

    mask = mask Or OrVal

    Test = Hex(mask)

    Results = (num And mask)
    Test = Hex(Results)
    ' shift to the right
    For i = 1 To startBit
        ' overcome the stupid sign extension
        Results = Results \\ 2
        If (Results < 0) Then
            Results = Results And &H7FFFFFFF
        End If
        Test = Hex(Results)
    Next

    Bits = Hex(Results)
End Function
' Pads the given hex number with leading zeros
Function PadZeros(HexNum As String, size As Integer) As String
    Results = HexNum
    For i = 1 To size - Len(HexNum)
        Results = "0" + Results
    Next

    PadZeros = Results
End Function

'Converts a hex number to long
Function HexToDecimal(HexNum As String) As Long
    HexToDecimal = CLng("&H" & HexNum)
End Function

'Converts Decimal To Hex
Function DecimalToHex(num As Long) As String
    DecimalToHex = Hex(num)
End Function

Leave a Reply