xlf | xlfBinAdd1 function


xlfBinAdd1 - about the function


Description: returns a string value from the addition of two binary numbers

Syntax: xlfBinAdd(Bin1,Bin2)

Arguments: Bin1 (required): a positive binary integer.

Arguments: Bin2 (required): a positive binary integer.


Rules of binary addition


A + BSumCarry
0 + 0 0 0
0 + 1 1 0
1 + 0 1 0
1 + 1 0 1

Example: \(100101\) (37) + \(10101\) (21) = \(111010\) (58)


$$ \begin{array}{r} &1\; 0\; 0\; 1\; 0\;1\\ +&1\;0\;1\;0\;1\\ \hline &1\;1\;1\;0\;1\;0 \end{array} $$


xlfBinAdd1 - the VBA code



Code 1: Function xlfBinAdd1 returns a string value from the addition of two binary numbers
Function xlfBinAdd1(ByVal Bin1 As String, ByVal Bin2 As String) As Variant

' Variables: addition engine
Dim LenBin(1 To 2) As Integer
Dim Bin(1 To 2) As String

Dim Ans As String
Dim Carry As Integer, Carried As Integer

Dim i As Integer, NoLoops As Integer
Dim Tmp As Integer, Tmp1 As Integer, Tmp2 As Integer

' Variables: maintenance
Dim App As Application: Set App = Application

    Bin(1) = Bin1: Bin(2) = Bin2

    ' Validate Bin1 and Bin2
    ' Check for only 0's and 1's
    For i = 1 To 2
        If Len(Bin(i)) <> Len(App.Substitute(Bin(i), "0", "")) + Len(App.Substitute(Bin(i), "1", "")) Then
            xlfBinAdd1 = CVErr(xlErrValue)
            Exit Function
        End If
    Next i

    For i = 1 To 2
        LenBin(i) = Len(Bin(i))
    Next i

    NoLoops = App.Max(LenBin)

    For i = 1 To 2
        Bin(i) = App.Rept("0", NoLoops - LenBin(i)) & Bin(i)  ' pad leading zeros to equal number of binary digits
    Next i

    For i = NoLoops To 1 Step -1
        Tmp1 = Mid(Bin(1), i, 1)
        Tmp2 = Mid(Bin(2), i, 1)

        ' === Binary addition: apply rules
        If Tmp1 = 0 And Tmp2 = 0 Then       ' 0 + 0 = 0
            Tmp = 0: Carry = 0

        ElseIf Tmp1 = 0 And Tmp2 = 1 Then   ' 0 + 1 = 1
            Tmp = 1: Carry = 0

        ElseIf Tmp1 = 1 And Tmp2 = 0 Then   ' 1 + 0 = 1
            Tmp = 1: Carry = 0

        ElseIf Tmp1 = 1 And Tmp2 = 1 Then   ' 1 + 1 = 0 carry 1
            Tmp = 0: Carry = 1

        End If

        ' === Binary addition, build result string
        If Tmp = 0 And Carried = 0 Then         ' 0, 0
            Ans = 0 & Ans

        ElseIf Tmp = 0 And Carried = 1 Then     ' 0, 1
            Ans = 1 & Ans: Carried = 0

        ElseIf Tmp = 1 And Carried = 0 Then     ' 1, 0
            Ans = 1 & Ans

        ElseIf Tmp = 1 And Carried = 1 Then     ' 1, 1
            Ans = 1 & Ans: Carried = 0

        End If
            Carried = Carry
    Next i
    xlfBinAdd1 = Ans
End Function
'


Code 2: Sub TestxlfBinAdd1
Sub TestxlfBinAdd1()
Dim Ans As Variant

    Ans = xlfBinAdd1("100101", "10101")
    Stop

End Sub

xlf-binary-add
Fig 1: xlfAnimator - VBE F5 with Stop - mouse over variable to display value from code 2 line 5