This article was previously published under Q109260
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
The following sample program shows how to convert a decimal number into itsequivalent binary representation stored in a string.
This program accepts a nine-digit positive decimal number and returns a 32-character string that represents the number in binary notation. Negativenumbers are converted into the 32-digit, twos-complement binary format usedby long integers in Basic.
In decimal numbers (base-ten numbers), every decimal place is a powerof 10. Decimal digits can have values from zero to nine. In binary numbers(base-two numbers), every decimal place is a power of two. Binary digitscan only have values of 0 or 1.
Start a new project in Visual Basic. Form1 is created by default.
Add two text boxes to Form1. Make each text box more than 32 characters wide.
Double-click the Text1 text box to open its code window. Choose the Change event from the Proc box. Add the following code to the Text1 Change event:
Sub Text1_Change () Dim i As Long, x As Long, bin As String Const maxpower = 30 ' Maximum number of binary digits supported. text1.MaxLength = 9 ' Maximum number of decimal digits allowed. text2.Enabled = False ' Prevent typing in second text box. bin = "" 'Build the desired binary number in this string, bin. x = Val(text1.Text) 'Convert decimal string in text1 to long integer If x > 2 ^ maxpower Then MsgBox "Number must be no larger than " & Str$(2 ^ maxpower) text2.Text = "" Exit Sub End If ' Here is the heart of the conversion from decimal to binary: ' Negative numbers have "1" in the 32nd left-most digit: If x < 0 Then bin = bin + "1" Else bin = bin + "0" For i = maxpower To 0 Step -1 If x And (2 ^ i) Then ' Use the logical "AND" operator. bin = bin + "1" Else bin = bin + "0" End If Next text2.Text = bin ' The bin string contains the binary number. End Sub
Start the program, or press the F5 key. Enter decimal numbers into the first text box. The binary equivalent number displays in the second text box.
NOTE: This program converts negative decimal numbers into the internaltwos-complement binary format used by Basic. In that format, the left-mostbinary digit (the thirty-second digit in a long integer) will always be 1for a negative number and 0 for a positive number.