Search code examples
pythontwos-complementones-complement

How do you determine one's complement and two's complement in Python?


Here's what I have so far:

decimalEquivalent is variable that represents an integer.

#One's complement of the binary string is shown
onesComplement = bin(~decimalEquivalent)
print(f'The negative no (-{decimalEquivalent}) using 1\'s Complement: {onesComplement}')

#Two's complement of the binary string is shown
twosComplement = onesComplement + bin(1)
print(f'The negative no (-{decimalEquivalent}) using 2\'s Complement: {twosComplement}')

Could you help me figure out what I am doing wrong?

I was trying to determine one's complement and two's complement for an integer.


Solution

  • bin returns a string. You need to do all of your arithmetic before calling bin, or you'll just be concatenating strings. Consider

    #One's complement of the binary string is shown
    onesComplement = ~decimalEquivalent
    print(f'The negative no (-{decimalEquivalent}) using 1\'s Complement: {bin(onesComplement)}')
    
    #Two's complement of the binary string is shown
    twosComplement = onesComplement + 1
    print(f'The negative no (-{decimalEquivalent}) using 2\'s Complement: {bin(twosComplement)}')