Juggler_IN
Active Member
- Joined
- Nov 19, 2014
- Messages
- 349
- Office Version
- 2003 or older
- Platform
- Windows
I am facing an issue with a C++ code conversion to VBA. If you provide two binary strings the function outputs the addition of two strings in binary format.
For example, if a = 11 == "00001011" and b = 36 == 00100100, then a+b = 47 == 00101111. The function also outputs 00101111.
If we provide string input, say within 1,25 using RANDBETWEEN using DEC2BIN then this function in most instances gives the desired output except for few exceptions such as, if a = 11 == 00001011 and b = 35 == 00100011, then a+b = 46 and the output SHOULD be 00101110 but the function is EVALUATING to 00110010 == 50.
I am unable to decode the issue. Any thoughts?
My UDF is:
C++ source code is -- (The link below provides a online execution of this code with different values.)
The C++ source code is atBinary Addition
For example, if a = 11 == "00001011" and b = 36 == 00100100, then a+b = 47 == 00101111. The function also outputs 00101111.
If we provide string input, say within 1,25 using RANDBETWEEN using DEC2BIN then this function in most instances gives the desired output except for few exceptions such as, if a = 11 == 00001011 and b = 35 == 00100011, then a+b = 46 and the output SHOULD be 00101110 but the function is EVALUATING to 00110010 == 50.
I am unable to decode the issue. Any thoughts?
My UDF is:
VBA Code:
Private Function solve( _
ByVal a As String, _
ByVal b As String) As String
Dim na%, nb%
Dim carry%
Dim i%, j%, k%
Dim addA%, addB%, sum%
Dim u, v, ret$
ret = ""
na = VBA.Len(a)
nb = VBA.Len(b)
i = (na - 1)
j = (nb - 1)
carry = 0
ReDim u(0 To i)
ReDim v(0 To j)
For k = 0 To na - 1
u(k) = VBA.Mid(a, k + 1, 1)
Debug.Print u(k);
Next
Debug.Print
For k = 0 To nb - 1
v(k) = VBA.Mid(b, k + 1, 1)
Debug.Print v(k);
Next
Debug.Print
Do While ((i >= 0) Or (j >= 0))
If (i >= 0) Then
addA = (u(i) - VBA.ChrW(48))
Else
addA = 0
End If
If (j >= 0) Then
addB = (v(j) - VBA.ChrW(48))
Else
addB = 0
End If
sum = addA + addB + carry
carry = sum / 2&
sum = sum Mod 2&
ret = ret & "" & sum
i = (i - 1)
j = (j - 1)
Loop
If carry <> 0 Then
ret = ret & "" & carry
End If
solve = VBA.StrReverse(ret)
Exit Function
End Function
C++ source code is -- (The link below provides a online execution of this code with different values.)
Code:
class Solution {
public:
string solve(string a, string b){
string ret = "";
int na = a.size();
int nb = b.size();
int i = na - 1;
int j = nb - 1;
int carry = 0;
while(i >= 0 || j >= 0){
int addA = i >= 0 ? a[i] - '0' : 0;
int addB = j >= 0 ? b[j] - '0' : 0;
int sum = addA + addB + carry;
carry = sum / 2;
sum %= 2;
ret += to_string(sum);
i--;
j--;
}
if(carry)
ret += to_string(carry); reverse(ret.begin(), ret.end());
return ret;
}
};
main(){
string a = "10110", b = "10010"; Solution ob;
cout << ob.solve(a, b);
}
The C++ source code is atBinary Addition