Monday, April 10, 2006

Hex in Visual Basic

Someone asked me how could a Hex be represented in Visual Basic 6. Fortunately, there is a function that does this for us already. Its called Hex(), or Hex$(). It returns a string representing the hexadecimal equivalent of an integer. Of course, I prefer the C style representation of hex (either 0x00 or 00h), so I created a function that does this for me. Below is the code demonstrating this. For this, there is a small form with a textbox, a checkbox, and a label. The textbox will take in a number, the checkbox will determine which format to use, the long format of “0x00” or the short format of “00h”, and the label will display the result.

Option Explicit

Function convertToHex(n As Integer, longStyle As Boolean) As String
    If (longStyle) Then
        convertToHex = "0x" & Hex(n)
        convertToHex = Hex(n) & "h"
    End If
End Function

Private Sub Command1_Click()
    If (Check1.Value = Checked) Then
        Label1.Caption = convertToHex(Text1.Text, True)
        Label1.Caption = convertToHex(Text1.Text, False)
    End If
End Sub

Private Sub Form_Load()
    Text1.Text = &HFF
End Sub

Also notice in the Form_Load() method, I am hard coding the value of 255 (0xFF) into the textbox. The prefix of &H will force VB to take in Hex, but the value displayed in the textbox will be 255.


Anonymous said...

I had trouble finding code to go from Hex to Decimal. I found some code here ( but it was quite laborious, so rewrote it:

Public Function HexToDec(Hex As String) As Double
Dim i As Long
Dim n As Long
Dim k As Double

Hex = UCase(Hex)
n = Len(Hex)
k = 0 ' k = total sum
For i = 1 To n
k = k * 16 ' Shift k by 4 bits
k = k + Val("&H" & Mid(Hex, i, 1))
Next i

HexToDec = k
End Function

Hope someone finds it useful.

Unknown said...

easier... :

Public Function HexToDec(Hex As String) As Long
HexToDec = CLng("&H" & Hex)
End Function

Unknown said...

Oh, good man!! Thanks for that! I knew there had to be a better way.