【发布时间】:2014-04-04 13:49:55
【问题描述】:
您好,我是这里的新手,一般来说是编码方面的。我一直在研究将两个二进制数相加的代码,这些部分单独工作,但组合起来不工作。如果有人可以帮助我解决这个问题,我将不胜感激。另外,如果可以缩短它也会有所帮助,谢谢。
Class Form1
Dim intNum1 As Integer
Dim intNum2 As Integer
Dim intNum3 As Integer
Public Function BinaryToDecimalA(ByRef Binary As String) As Integer
Dim BinaryNumA As Integer
Dim BitCountA As Short
For BitCountA = 1 To Len(Binary)
BinaryNumA = BinaryNumA + (CDbl(Mid(Binary, Len(Binary) - BitCountA + 1, 1)) * (2 ^ (BitCountA - 1)))
Next BitCountA
BinaryToDecimalA = BinaryNumA
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum1 = (BinaryToDecimal((TextBox1.Text)))
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
TextBox1.MaxLength = 3
End Sub
Public Function BinaryToDecimal(ByRef Binary As String) As Integer
Dim BinaryNum As Integer
Dim BitCount As Short
For BitCount = 1 To Len(Binary)
BinaryNum = BinaryNum + (CDbl(Mid(Binary, Len(Binary) - BitCount + 1, 1)) * (2 ^ (BitCount - 1)))
Next BitCount
BinaryToDecimal = BinaryNum
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum2 = (BinaryToDecimal((TextBox2.Text)))
End Sub
Private Sub TextBox2_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
TextBox2.MaxLength = 3
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
intNum1 = Integer.Parse(TextBox1.Text)
intNum2 = Integer.Parse(TextBox2.Text)
intNum3 = intNum1 + intNum2
End Sub
Private Sub intNum3_TextChanged(sender As Object, e As EventArgs) Handles TextBoxAns.TextChanged
Dim i As Long, x As Long, bin As String
Const maxpower = 7
TextBoxAns.Enabled = False
bin = ""
x = Val(intNum3)
If x > 2 ^ maxpower Then
MsgBox("Number must be no longer than " & Str$(2 ^ maxpower))
TextBoxAns.Text = ""
End If
If x < 0 Then bin = bin + "1" Else bin = bin + "0"
For i = maxpower To 0 Step -1
If x And (2 ^ i) Then
bin = bin + "1"
Else
bin = bin + "0"
End If
Next
TextBoxAns.Text = bin
End Sub
End Class
【问题讨论】:
-
dim a As Integer = Convert.ToInt32("101010", 2) + Convert.ToInt32("1000101", 2)