Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Made a method, where you put in 2 binary strings, then it returns the sum of those strings, as a string.
Now the problem is the code sometimes adds 2 instead of 0, when adding bits together. But only when facing bigger binary numbers. Like
"101011001101110101" + "111110010000111010" = "1121201011112101111"

What would be the problem?

What I have tried:

This is my code.

static String binarnoSestej(String s, String b){
    long st1 = Long.parseLong(s);
    long st2 = Long.parseLong(b);

    int i = 0;
    int prenos = 0;
    int[] koncnoSt = new int[s.length() + b.length()];

    while (st1 != 0 || st2 != 0) {
        koncnoSt[i++] = (int) (prenos + (st1 % 10 + st2 % 10) % 2);
        prenos = (int) ((st1 % 10 + st2 % 10 + prenos) / 2);
        st1 = st1 / 10;
        st2 = st2 / 10;
    }
    if (prenos != 0) {
        koncnoSt[i++] = prenos;
    }
    --i;
    String bit = "";
    while (i >= 0) {
        bit = bit + koncnoSt[i--];
    }
    return bit;
}
Posted
Updated 18-Mar-21 8:21am
Comments
Daniel Pfeffer 18-Mar-21 13:55pm    
I don't see anywhere that you handle the carry correctly. Binary addition is (for each bit):

given carry, a(i), b(i), calculate new carry and c(i) = a(i) + b(i).

c(i) = a(i) ^ b(i) ^ carry
new carry = (a(i) & b(i)) | (a(i) & carry) | (b(i) & carry)

for bits 0 of the operands, set carry = 0.

Note that this is a special case of the generic code for addition in an arbitrary base.
Richard Deeming 19-Mar-21 5:31am    
Aren't you missing the radix parameter to the Long.parseLong calls?
long st1 = Long.parseLong(s, 2);
long st2 = Long.parseLong(b, 2);

Without it, your strings are parsed as decimal numbers, not binary.

1 solution

Quote:
Why would my code add 2 when doing binary addition?

try to replace
Java
koncnoSt[i++] = (int) (prenos + (st1 % 10 + st2 % 10) % 2);

with
Java
koncnoSt[i++] = (int) ((prenos + st1 % 10 + st2 % 10) % 2);
 
Share this answer
 
Comments
Member 14631234 18-Mar-21 16:07pm    
Yes, this worked, thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900