1

二进制补码是当您反转位然后添加二进制 1 位时。所以例如...

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

另一个显示溢出情况的例子......

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

在 python 中实现这一点的最佳方法是什么。到目前为止,我有这段代码,但我希望它更有效,因为我使用这种方法太多了。

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')

我的问题是,我可以优化这个算法吗,因为目前它的运行速度太慢,以至于我必须运行它的二进制代码量。

4

3 回答 3

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

我认为这应该可以解决问题

于 2013-05-29T12:01:55.727 回答
1

尝试这个:

x = 0b11001100
complement = abs(~x) + 0b1
print bin(complement)
于 2013-05-29T13:34:32.963 回答
0

使用位串

>>> from bitstring import BitArray
>>> a = BitArray(bin='111111111111')
>>> a.int
-1
于 2013-05-29T12:34:11.453 回答