Article ID: 109260
Article Last Modified on 12/9/2003
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
Decimal Value Binary Value ----------------------------- 0 00000000000000000000000000000000 21 00000000000000000000000000010101 1024 00000000000000000000010000000000 32767 00000000000000000111111111111111 32768 00000000000000001000000000000000 65536 00000000000000010000000000000000 16777216 00000001000000000000000000000000 999999999 00111011100110101100100111111111 -1 11111111111111111111111111111111 -3 11111111111111111111111111111101
Additional query words: 2.00 3.00
Keywords: KB109260