Binary Addition using a bool vector

So I'm using a bool vector to store binary numbers, and I'm trying to perform operations on the vectors. Currently, my addition operator doesn't seem to be doing exactly what I'd expect it to do.

When writing the code I also noticed that the 2 vectors could be of different sizes so i did a number of if statements to account for that. I didn't include it here because I thought it might get a bit confusing. But the main question is how exactly do i write the code for binary addition and whether im basically right or on the right track.

The main portion of the calculation is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Integer& Integer::operator+=(const Integer& rhs) {  

  Integer sum = 0; //when this variable is created, it initializes a boolean vector sum = {0}

        for (int i = 0; i < bit.size(); i++){

                sum.bit.push_back(0);
                
                if((bit[i] + rhs.bit[i] + sum.bit[i]) == 3) {
                    sum.bit.push_back(1);
                    sum.bit[i] = 1;
                }
                
                if((bit[i] + rhs.bit[i] + sum.bit[i]) == 2)
                    sum.bit.push_back(1);
                
                if((bit[i] + rhs.bit[i] + sum.bit[i]) == 1)
                    sum.bit[i] = 1;

Last edited on
You have to add a bit once per loop, in your code it can add it twice.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Integer& Integer::operator+=(const Integer& rhs)
{  

    Integer sum = 0; //when this variable is created, it initializes a boolean vector sum = {0}

    int carry = 0;

    for (int i = 0; i < bit.size(); i++)
    {
        switch(bit[i] + rhs.bit[i] + carry)
        {
        case 0: sum.bit.push_back(0); carry = 0; break;
        case 1: sum.bit.push_back(1); carry = 0; break;
        case 2: sum.bit.push_back(0); carry = 1; break;
        case 3: sum.bit.push_back(1); carry = 1; break;
        }
    }
}


Something like that, if you are trying to implement a large integer there is probably a more efficient way to do it. But this is good enough, i guess.
Topic archived. No new replies allowed.