I have been learning about Bitwise operations today and I learned that Not (~) inverses all bits, e.g.:
01010
to
10101
which means ~10 should be -5 but instead I have seen that it is -11 (per the python command line) which is
01010
to
11011
only two of the bits have been inverted. Can anybody explain why it isn't 10101?
EDIT: After looking on my calculator I understand it a little better, But my own code for determining binary and ints is still being confused. Entering in (in byte mode) 11110101 gives me -11 but the same entered 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) #make positive!
biNum = ""
while iLoopNum:
biNum += str(iLoopNum%2)
iLoopNum /= 2
return bSign + biNum[::-1] if not bUnsigned else biNum[::-1] + "u"
can one of you explain that?
The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0. Both operands to the bitwise AND operator must have integral types.
They are bit shift operator which exists in many mainstream programming languages, << is the left shift and >> is the right shift, they can be demonstrated as the following table, assume an integer only take 1 byte in memory.
Python's bitwise NOT operator ~x inverts each bit from the binary representation of integer x so that 0 becomes 1 and 1 becomes 0. This is semantically the same as calculating ~x == -x-1 . For example, the bitwise NOT expression ~0 becomes -1 , ~9 becomes -10 , and ~32 becomes -33 .
In Python >> is called right shift operator. It is a bitwise operator. It requires a bitwise representation of object as first operand. Bits are shifted to right by number of bits stipulated by second operand. Leading bits as towards left as a result of shifting are set to 0.
Assuming that values are 32 bits, 10 is
00000000000000000000000000001010
and if you invert all those bits, you get
11111111111111111111111111110101
or -11. Because it's a 2's complement system!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With