我今天一直在学习按位运算,我了解到 Not (~) 反转所有位,例如:
01010
to
10101
这意味着〜10应该是-5,但我看到它是-11(根据python命令行),它是
01010
to
11011
只有两个位被反转。谁能解释为什么不是10101?
编辑:看了我的计算器后,我对它的理解更好了,但是我自己确定二进制和整数的代码仍然很困惑。输入(以字节模式)11110101 给我 -11 但在我的代码中输入的相同给我 -117:
def binaryToInt(biNum, bUnsigned = False):
iNum = 0
bSign = int(biNum[0]) if not (bUnsigned or biNum[-1] == "u") else 0
biNum = biNum[(1 if not (bUnsigned or biNum[-1] == "u") else 0):(len(biNum) if biNum[-1] != "u" else -1)]
for i in xrange(len(biNum)):
iNum += int(biNum[i]) * 2**(len(biNum) - 1 - i)
return (iNum if not bSign else -iNum)
def intToBinary(iNum, bUnsigned = False):
bSign = "1" if iNum < 0 else "0"
iLoopNum = int((iNum ** 2) ** 0.5) #make positive!
biNum = ""
while iLoopNum:
biNum += str(iLoopNum%2)
iLoopNum /= 2
return bSign + biNum[::-1] if not bUnsigned else biNum[::-1] + "u"
你们中的一个可以解释一下吗?