按位&输出1和0以外的数字

时间:2014-09-13 12:21:48

标签: python python-3.x bit-manipulation

我必须'&'两个98长度位消息,但是当我输出时包含1和0以外的数字。有人可以看到我搞砸的地方:

print("The binaryCode of the input message is:", binaryCode)
print("The gsBinary is:", gsBinary)
print(len(gsBinary), len(binaryCode))

newStr = int(gsBinary) & int(binaryCode)
print("The result of anding the gsBinary & binaryCode was:", newStr)

这是运行时的当前输出:

The binaryCode of the input message is: 11001111110010110010111000011110100100000110100011000011110011110100010000011001101110101110111011

The gsBinary is: 11001111110010110010111001011101110110110011000011110111111001111011101111001110010011001011110010

98 98

The result of anding the gsBinary & binaryCode was: 11001111110010110010110999119920984020956932636701193212439574622352446504985730534177701743362082

为什么newStr打印长度为98的字符串,其值不是1&如果两个输入字符串只包含一个且为零,则为0?

1 个答案:

答案 0 :(得分:7)

您需要将字符串解释为不是10基整数,而是解释为2基整数:

newinteger = int(gsBinary, 2) & int(binaryCode, 2)

注意int()的第二个参数; 101被解释为整数5而不是101。

输出不是字符串;它是另一个整数,因此您需要将其转换回二进制的字符串表示形式:

newstr = format(newinteger, 'b')

演示:

>>> binaryCode = '11001111110010110010111000011110100100000110100011000011110011110100010000011001101110101110111011'
>>> gsBinary = '11001111110010110010111001011101110110110011000011110111111001111011101111001110010011001011110010'
>>> newinteger = int(gsBinary, 2) & int(binaryCode, 2)
>>> format(newinteger, 'b')
'11001111110010110010111000011100100100000010000011000011110001110000000000001000000010001010110010'