Convert Hexadecimal numbers

Convert Hexadecimal numbers

While Visual Basic offers the Hex$ function that converts a decimal value into its hexadecimal equivalent number, it seems that the inverse function is missing. Not true. Try out this one-liner:

Function HexToDec(HexValue As String) As Long    HexToDec = Val("&H" & HexValue)End Function

UPDATE The code in the original tip always tries to return an Integer value, which means that, for example, “FFFF” is converted to -1 instead of 65,535. The following new versions fixes this behavior, while still giving you the capability to convert to an integer:

Function HexToDec(HexValue As String, Optional ToInteger As Boolean) As Long    If ToInteger Then        ' convert to an integer value, if possible.         ' Use CInt() if you want to *always* convert to an Integer        HexToDec = Val("&H" & HexValue)    Else        ' always convert to a Long. You can also use the CLng() function.        HexToDec = Val("&H" & HexValue & "&")    End IfEnd Function

Thanks to Joe Hartman for spotting the problem with the original routine and suggesting the solution.

See also  Monetize TikTok For Your Business

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist