当你反转位然后添加二进制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')
我的问题是,我可以优化这个算法,因为目前运行速度太慢,无法运行它。
答案 0 :(得分:5)
x=int(a,2)
num_bits = 10
print x - (1 << num_bits)
我认为这应该可以解决问题
答案 1 :(得分:1)
试试这个:
x = 0b11001100
complement = abs(~x) + 0b1
print bin(complement)
答案 2 :(得分:0)
使用bitstring包
>>> from bitstring import BitArray
>>> a = BitArray(bin='111111111111')
>>> a.int
-1