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

标签 python performance twos-complement

<分区>

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

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

最佳答案

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

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

关于Python - 实现二进制补码的最有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16813262/

相关文章:

python - 为什么 numpy 在查找矩阵中的非零元素方面更快?

performance - 如何提高在 DolphinDB 中计算希腊语的性能?

mysql - 查询效率——从表中选择最新的2条 “group/batch”记录

java - 错误: The literal 1111111111111000 of type int is out of range

java - 带符号字节的 6502 的条件分支指令?

python - 转换为 unicode 的正确方法是什么?

python - concurrent.futures.ThreadPoolExecutor.map 比 for 循环慢

performance - 算法 : how do divide-and-conquer and time complexity O(nlogn) relate?

java - 为什么 -2>>>1 在 Java 中等于 2147483647

Python查找列表中最大值的索引