How-To... - Convert Decimal to Binary

001100 110001 111011 00001 - Binary, the language of the computer. When you press a key, the ASCII key code is converted into Binary so that the computer can understand what key was pressed and act accordingly.

This How-To will show you how to convert a decimal number into its binary value.

On a new form add three text boxes - txtDecimal, txtMax, txtBinary. Give txtMax a MaxLength of 2 and the other text boxes a MaxValue of 30. Add a command button and 3 labels.

Form Code

Add the following code to the Click event of the command button:-

'Declare variables...
'lCount(thats L) -- used to loop...
'lConvert -- the decimal to be converted...
'sBinary -- the final answer, in binary format...
'iMaxpower -- maximum length of Binary digits...

Dim lCount As Long, lConvert As Long, sBinary As String
Dim iMaxpower As Integer

'If txtMax is empty...
If txtMax.Text = "" Then

'Display a message box...
MsgBox "Please Enter A Value!"

'and exit sub...
Exit Sub
End If

iMaxpower = txtMax.Text

sBinary = "" 'Build the desired binary number in this string...
lConvert = Val(txtDecimal.Text) 'Convert decimal string in txtDecimal to long integer...

'^ is used to raise 2 to the power of iMaxpower...
If lConvert > 2 ^ iMaxpower Then

'Display an error box...
MsgBox "Number must be no larger than " & Str$(2 ^ iMaxpower)

'Exit the sub...
Exit Sub

End If

'Here is the heart of the conversion from decimal to binary...

'Negative numbers have "1" in the 32nd leftmost digit...
If lConvert < 0 Then sBinary = sBinary + "1" Else sBinary = sBinary + "0"

For lCount = iMaxpower To 0 Step -1
If lConvert And (2 ^ lCount) Then 'Use the logical "AND" operator...
sBinary = sBinary + "1"
Else
sBinary = sBinary + "0"
End If
Next

txtBinary.Text = sBinary 'The bin string contains the binary number...

Run the program and enter a value in the decimal box(e.g. 128) and a value in the Max box(e.g. 7 for 128) and click the button. For this example, the binary value would be 010000000

You can download this example by clicking here


This site is Copyright © 1999 of David Cowan. VB How-To, Dodgesoft and DodgeSoft Productions is Copyright © 1999 of David Cowan. Source-code and programs are copyright of their respective owners. For a messageboard, click here