My requirement is to add two binary numbers, say "1001" and "0101" as binary1
and binary2
.
Partial Class Default2
Inherits System.Web.UI.Page
Dim carry As Boolean = False ' Boolean variable to hold the carry if occured
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim binary1 As String = TextBox1.Text 'First binary number
Dim binary2 As String = TextBox2.Text 'Second binary number
Dim result As String = "" 'to store the result
For i As Integer = Len(binary1 ) - 1 To 0 Step -1
result = bin_add(getbyte(binary1 , i), getbyte(binary1, i)) & result ' calling function
Next
If carry = True Then
result = "1" & result 'if a carry remains add it to the MSB
End If
MsgBox(rslt) 'Display the result
End Sub
Public Function bin_add(b1 As Boolean, b2 As Boolean) As String'Function which performs the addition of each single bits form the two inputs which is passed from the calling function
Dim result As Boolean
If b1 AndAlso b2 = True Then 'both values are 1/true
If carry = True Then
result = True
carry = True
Else
result = False
carry = True
End If
ElseIf b1 = False And b2 = False Then 'Both are 0/false
If carry = True Then
result = carry
carry = False
Else
result = False
carry = False
End If
Else
If carry = True Then
result = False
carry = True
Else
result = True
carry = False
End If
End If
If result = True Then
Return "1" 'return 1 for Boolean true
Else
Return "0" 'return 0 for Boolean false
End If
End Function
Private Function getbyte(s As String, ByVal place As Integer) As String'Function for getting each individual letters from the input string. i got it from net.
If place < Len(s) Then
place = place + 1
getbyte = Mid(s, place, 1)
Else
getbyte = ""
End If
End Function
End Class
Notes:
- It gives good results for me only if the no. of digits in both numbers are the same.
Question:
How can I improve the code? Especially, how can I reduce the length of code?
0
s so that it has the same length (I'm assuming only positive numbers here) \$\endgroup\$ – tim Aug 18 '14 at 9:49And
Keyword does bitwise addition? Once the binary representation is converted to an integer, this should be trivial. \$\endgroup\$ – RubberDuck Aug 18 '14 at 10:26