Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HEX string to Unsigned INT (VBA)

Tags:

vba

ms-access

In MSACCESS VBA, I convert a HEX string to decimal by prefixing the string with "&h"

?CLng("&h1234")
4660
?CLng("&h80000000")
-2147483648 

What should I do to convert it to an unsigned integer?

Using CDbl doesn't work either:

?CDbl("&h80000000")
-2147483648 
like image 689
SBF Avatar asked Oct 26 '25 05:10

SBF


1 Answers

Your version seems like the best answer, but can be shortened a bit:

Function Hex2Dbl(h As String) As Double
    Hex2Dbl = CDbl("&h0" & h) ' Overflow Error if more than 2 ^ 64
    If Hex2Dbl < 0 Then Hex2Dbl = Hex2Dbl + 4294967296# ' 16 ^ 8 = 4294967296
End Function

Double will have rounding precision error for most values above 2 ^ 53 - 1 (about 16 decimal digits), but Decimal can be used for values up to 16 ^ 12 - 1 (Decimal uses 16 bytes, but only 12 of them for the number)

Function Hex2Dec(h)
    Dim L As Long: L = Len(h)
    If L < 16 Then               ' CDec results in Overflow error for hex numbers above 16 ^ 8
        Hex2Dec = CDec("&h0" & h)
        If Hex2Dec < 0 Then Hex2Dec = Hex2Dec + 4294967296# ' 2 ^ 32
    ElseIf L < 25 Then
        Hex2Dec = Hex2Dec(Left$(h, L - 9)) * 68719476736# + CDec("&h" & Right$(h, 9)) ' 16 ^ 9 = 68719476736
    End If
End Function
like image 144
Slai Avatar answered Oct 28 '25 03:10

Slai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!