将十六进制字符串转换为无符号INT(VBA) [英] Convert HEX string to Unsigned INT (VBA)

查看:441
本文介绍了将十六进制字符串转换为无符号INT(VBA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MSACCESS VBA中,我通过在字符串前面加上& h将十六进制字符串转换为十进制

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?

使用CDbl也不起作用:

Using CDbl doesn't work either:

?CDbl("&h80000000")
-2147483648 


推荐答案

您的版本似乎是最好的答案,但可以缩短一点:

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

<对于大多数高于2 ^ 53-1的值,code> Double 将具有舍入精度错误(大约16个十进制数字),但十进制可以用于最大16 ^ 12-1(十进制使用16个字节,但仅使用12个字节)

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

这篇关于将十六进制字符串转换为无符号INT(VBA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆