How do I convert a Hexidecimal number to Decimal

D

Douglas J. Steele

Val("&H16") will give you 22.

If your Hex value is in a variable, you can use something like Val("&H" &
strHexValue)
 
N

Nikos Yannacopoulos

If you look in Access help, there is a built-in function called HEX2DEC
which does exactly that, but there's awarning it may not work in the absense
of a certain DLL - and indeed it doesn't on my machine. Therefore I have
written my own function in VBA to do it. Just paste in a general module:

Function H2D(vHex As String)
ttl = "Conversion Error"
sl = Len(vHex)
If sl > 14 Then
msg = "HEX number length must be up to 14 characters!"
MsgBox msg, vbCritical, ttl
H2D = "*Error"
Exit Function
End If
For i = sl To 1 Step -1
d = Mid(vHex, sl - i + 1, 1)
Select Case d
Case "0" To "9"
dv = Val(d)
Case "A" To "F"
dv = Asc(UCase(d)) - 55
Case Else
msg = "Invalid character in HEX number!"
MsgBox msg, vbCritical, ttl
H2D = "*Error"
Exit Function
End Select
v = v + dv * 16 ^ (i - 1)
Next
H2D = v
End Function


Then you can call it from anywhere in your project as H2D(argument).

HTH,
Nikos
 
N

Nikos Yannacopoulos

It was that simple, and help points to a non-working function!!!

Thanks Doug!
 
T

Tim Ferguson

How do I convert a Hexidecimal number to Decimal

Okay: if this is a competition, here's mine... no comments as they are left
as an exercise for the reader :)

Public Function HexToDec(SomeHex As String) As Long

Const c_strDigits = "0123456789ABCDEF"

If Len(SomeHex) = 0 Then
HexToDec = 0

Else
HexToDec = InStr(c_strDigits, Right$(SomeHex, 1)) - 1 + _
HexToDec(Left$(SomeHex, Len(SomeHex) - 1)) * 16

End If

End Function

Best wishes


Tim F
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top