Skip to main content
 首页 » 编程设计

Python之实现二进制补码的最有效方法

2025年05月04日16zhenyulu

<分区>

二进制补码是将位取反然后添加二进制 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') 

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