views:

101

answers:

4

Hello,

I am trying to add the Two's Complement to a Binary number represented with a string. Assuming the string has already been flipped, how would I go about "adding" 1 to the last character, and replacing the other characters in the string as needed?

Example: 100010 is flipped to 011101, and is represented as a string. How would you apply the Two's Complement to the 011101 string?

One part of this that really has me puzzled is if the user enters a binary number that, when the two's complement is applied, involves a lot of carrying.

+1  A: 

I'd just do it as a number, then convert it back.

def tobin(x, count=8):
    # robbed from http://code.activestate.com/recipes/219300/
    return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))

def twoscomp(num_str):
    return tobin(-int(num_str,2),len(num_str))

print twoscomp('01001001') # prints 10110111
print twoscomp('1000')     # prints 1000 (because two's comp is cool like that)
print twoscomp('001')      # prints 111
Nick T
A: 

Have a look here for some info

ghostdog74
+1  A: 

Just for variety, here's yet another way based on the fact the Two's Complement is defined as the One's Complement plus one. This cheats a little and converts the intermediate one's complement string value into an integer to add one to it, and then converts it back to a binary string using the new built-in bin() function added in Python 2.6.

def onescomp(binstr):
    return ''.join('1' if b=='0' else '0' for b in binstr)

def twoscomp(binstr):
    return bin(int(onescomp(binstr),2)+1)[2:]

print twoscomp('01001001') # prints 10110111
print twoscomp('011101')   # prints 100011
print twoscomp('001')      # prints 111
martineau
When trying to use "print twoscomp(<my flipped string>), I get an error saying that strings cannot be called.
Just a Student
@Anonymous: Sorry I cannot reproduce the problem you describe. What version of Python are you using and what exactly are you passing to `twoscomp()` as the argument (i.e `<my flipped string>`)?
martineau
@Anonymous: Here's a shot in the dark, but my wild guess is that you might have created a string variable named `bin`, which hides the built-in `bin` function. That, or possibly `int`. Change your variable name (to `bin_` perhaps), and give it another shot.
Nick T
+1  A: 

if you want to do it without converting back to a number, start from the right of the string until you find the first 1, then flip all chars to its left.

klaus