I found out about Bitwise operations today, and I found out that Not (~) inverts all bits, for example:
01010 to 10101
which means that ~ 10 should be -5, but instead, I saw it was -11 (on the python command line), which is equal to
01010 to 11011
only two of the bits were inverted. Can anyone explain why this is not 10101?
EDIT: after looking at my calculator, I understand this a little better, but my own code for determining binary and ints is still confused. Entering (in byte mode) 11110101 gives me -11, but the same as in my code gives -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)
can any of you explain this?
source share