devxlogo

Converting a Hex String to Decimal

Converting a Hex String to Decimal

Question:
I have a database of strings of hex numbers and I want to convert them to decimal. There doesn’t seem to be a function for it, but can you go the other way with the HEX function?

e.g. "A" converts to 10.e.g. "AB" needs to convert to 171.

Answer:
Here’s a little snippet of code that will do the trick:

Sub Main()   Const Original = "AB12C"   Dim lngValue As Long   Dim strChar As String   Dim intCharValue As Integer   Dim i As Integer   For i = 0 To Len(Original) - 1      strChar = Mid(Original, Len(Original) - i, 1)      Select Case strChar      Case 0 To 9         intCharValue = Int(strChar)      Case "A", "B", "C", "D", "E", "F"         intCharValue = Asc(strChar) - 55      End Select      lngValue = lngValue + (intCharValue * (16 ^ i))   Next i   End Sub

When you’re finished, lngValue will have the decimal value of the constant specified.


On Feb. 18th, 2000, DevX reader Kevin Palmer suggested this alternative to the above code:

Sub Main()Const Original = "AB12C"Dim lngValue As Long lngValue = Val( "&H" & Original) End Sub 

On Feb. 22nd, 2000, DevX reader Eric Hood responded:

Basic has a conversion method available:

	d = val("&H" + h$)

where h$ = the hexidecimal valueand d = decimal value.
Example:

?val("&H3F") 63 

On Feb. 23rd, 2000, DevX reader Bryan Hapeman responded:

I was able to convert a hex string to decimal with the following code:

Dim Hex_String as StringDim Number as Double Number = val("&h" & Hex_String)

Doesn’t that work?


See also  Why ChatGPT Is So Important Today
devxblackblue

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