How To Convert Hexadecimal Numbers to Long Integer
A = Val("1234") ' performs decimal conversion A = Val("7FFF") ' results in 7 - the F's are ignored A = Val("&H7FFF") ' performs hexadecimal conversion
Integer TrapIf you are assigning the results of the conversion to a Long integervariable, you will probably only want numbers in the range 80000000 toFFFFFFFF to be treated as negative numbers. However, without taking specialprecautions, numbers in the range 8000 to FFFF will also be treated asnegative.
This occurs because numbers with four or fewer digits are convertedto signed 2-byte integers. When the signed integer intermediate value isconverted to a Long (or 4-byte) integer, the sign is propagated.
Visual Basic 4.0/Access 95 and LaterBy appending the "&" Long suffix to the hexadecimal string, even smallnumbers are treated as Long. The following function performs theconversion correctly:
Function HexToLong(ByVal sHex As String) As Long HexToLong = Val("&H" & sHex & "&") End Function
Visual Basic 3.0/Access 2.0 and EarlierThe method illustrated above will not work in Microsoft Visual Basic 3.0 orearlier for hexadecimal numbers greater or equal to 80000000. Please seethe REFERENCES section of this article for more information.
Because this problem does not occur with numbers that fall in the IntegerTrap range, the alternate function given below adds error trapping to tryagain without the appended "&" Long suffix:
Function HexToLong(ByVal sHex As String) As Long On Error Resume Next HexToLong = Val("&H" & sHex & "&") If Err Then On Error Goto 0 HexToLong = Val("&H" & sHex) End If End Function
A = HexToLong("8000")
Microsoft Visual Basic 4.0 ReadMe topic: Coercion of Hexadecimal Values
For more information, please see the following article in the MicrosoftKnowledge Base:
Article ID: 161304 - Last Review: 12/04/2015 15:58:38 - Revision: 3.2
- kbnosurvey kbarchive kbhowto KB161304