Python - Most effective way to implement two's complement? [duplicate]

*爱你&永不变心* 提交于 2019-12-23 02:58:21

问题


Two's complement is when you inverse bits then add a binary 1 digit. So for example...

0011001
apply two's complement
1. inverse the bits, 1100110
2. add a binary digit, 1100110 + 1 = 1100111

Another example to show overflow situation...

1001100
apply two's complement
1. inverse the bits, 0110011
2. add a binary digit, 0110011 + 1 = 0110100

What would be the best way to implement this in python. So far I have this code, but I would like it to be more efficient because I'm using this method too much.

def toTwosComplement(binarySequence):
    convertedSequence = [0] * len(binarySequence)
    carryBit = 1
    # INVERT THE BITS
    for i in range(0, len(binarySequence)):
        if binarySequence[i] == '0':
            convertedSequence[i] = 1
        else:
            convertedSequence[i] = 0

    # ADD BINARY DIGIT 1

    if convertedSequence[-1] == 0: #if last digit is 0, just add the 1 then there's no carry bit so return
            convertedSequence[-1] = 1
            return ''.join(str(x) for x in convertedSequence)

    for bit in range(0, len(binarySequence)):
        if carryBit == 0:
            break
        index = len(binarySequence) - bit - 1
        if convertedSequence[index] == 1:
            convertedSequence[index] = 0
            carryBit = 1
        else:
            convertedSequence[index] = 1
            carryBit = 0

    return ''.join(str(x) for x in convertedSequence)

if __name__ == '__main__':
    print toTwosComplement('00110010101101001')

My question is, can I optimise this algorithm because at the moment it is running too slow for the amount of binary code I have to run it through.


回答1:


x=int(a,2)
num_bits = 10
print x - (1 << num_bits)

I think this should solve the problem




回答2:


Try this:

x = 0b11001100
complement = abs(~x) + 0b1
print bin(complement)



回答3:


using bitstring package

>>> from bitstring import BitArray
>>> a = BitArray(bin='111111111111')
>>> a.int
-1


来源:https://stackoverflow.com/questions/16813262/python-most-effective-way-to-implement-twos-complement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!