首页 文章

Python - 实现两个补码的最有效方法? [重复]

提问于
浏览
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')

我的问题是,我可以优化这个算法,因为目前运行它的二进制代码量太慢了 .

3 回答

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

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

  • 1

    试试这个:

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

    使用bitstring

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

相关问题