Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating hex values w/ consistant zero padding

Status
Not open for further replies.

JeffAtBDK

Programmer
Oct 30, 2002
5
US
Enjoy

Function HexPad(Value As Long, Width As Integer) As String
Select Case Width
Case Is = 8
HexPad = IIf(Value < 16, "0", "") & Hex$(Value)
Case Is = 16
HexPad = IIf((Value < 16), "000", _
IIf((Value < 256), "00", _
IIf((Value < 4096), "0", ""))) & Hex$(Value)
Case Is = 32 'no larger than +2147483647
HexPad = IIf((Value < 16), "0000000", _
IIf((Value < 256), "000000", _
IIf((Value < 4096), "00000", _
IIf((Value < 65535), "0000", _
IIf((Value < 1048575), "000", _
IIf((Value < 16777215), "00", _
IIf((Value < 268435455), "0", _
""))))))) & Hex$(Value)
End Select
End Function
 
Here's another way to accomplish the same thing. This function will determine the data type of the variable passed in and return an appropriate string.

Code:
Public Function HexPad(ByVal Value As Variant) As String
    
    Select Case TypeName(Value)
        Case "Long"
            HexPad = VBA.Right$("00000000" & Hex(Value), 8)
        Case "Integer"
            HexPad = VBA.Right$("0000" & Hex(Value), 4)
        Case "Byte"
            HexPad = VBA.Right$("00" & Hex(Value), 2)
        Case Else
            HexPad = "Unknown"
    End Select
    
End Function

You can test it with the following code
Code:
    Dim iLong As Long
    Dim iInteger As Integer
    Dim iByte As Byte
    
    iByte = 255
    iInteger = iByte
    iLong = iByte
    
    Call MsgBox(HexPad(iLong))
    Call MsgBox(HexPad(iInteger))
    Call MsgBox(HexPad(iByte))
    
    iByte = 0
    iInteger = iByte
    iLong = iByte
    Call MsgBox(HexPad(iLong))
    Call MsgBox(HexPad(iInteger))
    Call MsgBox(HexPad(iByte))



-George

Strong and bitter words indicate a weak cause. - Fortune cookie wisdom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top