1+1 is 10 in binary and then you carry over the 1. I was wondering how to do that with Python? I was able to invert the binary and determine the sum of the rightmost bit and if it's 2, the rightmost digit would become 0. This is where I'm stuck at. I don't know how to carry over the 1. I was thinking of using the for function, and let it start from the right to the left using string indexing, but it gave me an error (TypeError: 'builtin_function_or_method' object is unsubscriptable).

This is part of the code that does what I just described.

elif s < bit:
        oldbitstring = str(int('1'*(bit-s) + b))
        bitstring = str(int('1'*(bit-s) + b) + 1)
        if int(bitstring[-1]) == 2:
            oldbitstring = int(oldbitstring) - 1
            print oldbitstring

*note bit would be the number of bits the user inputs. s would be the length of the binary after the decimal is converted.

So the idea is, you have two binary numbers represented as strings, and then you want to add them?

I'm not seeing any obvious errors in the code above.

So the idea is, you have two binary numbers represented as strings, and then you want to add them?

I'm not seeing any obvious errors in the code above.

No, not exactly. What I"m trying to do is two bit complement.

So for example, I want to determine the two bit complement of 10 with 4 bits.

1010 would be the binary of 10.

1010 --> 0101
1<-----carry over 1, since 1+1 is 10 in binary terms.
0101
+ 1
----------
0

And so forth. That's what I'm trying to do with the code, but I'm stuck at the carrying over of the number 1.

**sorry, the addition table thing won't show up probably. That carried-over 1 is suppose to be above 0(the second digit from the right).

1. Make carry=1, and newBitString=""
2. Calculate sum of carry and last (rightmost) bit of the BitString.
If the sum equals to 2 then make lastBit=0 and carry=1;
otherwise make lastBit = sum and carry=0. Append lastBit
to the left of newBitString.
3. Repeat step 2 for the second to the last bit of the BitString, and
so on (namely for all bits from right to left).
4. Return newBitString as the result.

Here's the algorithm i'm trying to replicate. Adding 1 to a bitString.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.