How to Convert Hex to Binary in Visual Basic
- 1). Open Visual Basic and click on "File" in the Main Menu. Click on "New Project" in the drop-down menu and select "Standard EXE" as a type.
- 2). Double-click on the "Label" tool (represented by an "A") from the Toolbox on the left. Double-click on the TextBox (represented by the letters "ab"). Click and drag the TextBox so it is next to the Label. Use the "Properties" list to change the caption of the Label to "Enter Hex Number" and delete the letters in the Text caption of the Textbox.
- 3). Add a command button to the form by double-clicking on the Button tool (a small rectangle) and change the caption of this to read "Convert Hex to Binary." Drag this button below the two items you created in Step 2. Add two more Labels the same way, placing them below the command button and on the same line. Change the caption of the first Label to "The binary equivalent is" and delete the letters in the caption property of the second Label.
- 4). Click on "View" in the Main Menu and select "Code." In the code window, type the following:
Private Sub Command1_Click()
Dim HexNbr As String
Dim DecNbr As Integer
Dim Result As String
DecNbr = Val("&H" & Text1.Text)
Result = BinaryNbr(DecNbr)
Do While Len(Result) < 8
Result = "0" & Result
Loop
Label3.Caption = Result
End Sub - 5). Type in the following code below that in Step 4:
Function FirstConv(ByVal exp As Long) As Long
Static TempNbr(0 To 31) As Long, n As Integer
If TempNbr(0) = 0 Then
TempNbr(0) = 1
For n = 1 To 30
TempNbr(n) = TempNbr(n - 1) * 2
Next
TempNbr(31) = &H80000000
End If
FirstConv = TempNbr(exp)
End Function - 6). Enter these last code lines below the "End Function" in Step 5:
Function BinaryNbr(ByVal calc As Long) As String
Dim TempNbr As String, exp As Integer
TempNbr = String$(32, "0")
Do
If calc And FirstConv(exp) Then
Mid$(TempNbr, 32 - exp, 1) = "1"
calc = calc Xor FirstConv(exp)
End If
exp = exp + 1
Loop While calc
BinaryNbr = Mid$(TempNbr, 33 - exp)
End Function - 7). Use the "F5" key to run the application. Enter a number in the blank box next to "Enter a Hex Number" and click on "Convert Hex to Binary." If you entered the code correctly, you will see the result appear in the empty box next to "The Binary equivalent result is." If not, recheck the code.
Source...