Can somebody explain this example through binary digits?
>>> ~11
-12
Can somebody explain this example through binary digits?
>>> ~11
-12
Using 8 bit representation (you can use larger representations for the same results):
~11 => ~ b 00001011
Applying NOT operator yields (1 turns to 0 and vice versa):
~(b 00001011) => b 11110100
The result is negative (since the left most bit is the sign bit). To discover its value, apply 2's complement operator (see here):
b 11110100, negate bits:
b 00001011, add 1:
+ 1
----------
b 00001100 => 12
Meaning that the result was -12.
def toBinary(n):
return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])
toBinary(11) Returns
0000000000000000000000000000000000000000000000000000000000001011
toBinary(-12) Returns
1111111111111111111111111111111111111111111111111111111111110100
From Python Docs ~x : Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1. For More : https://wiki.python.org/moin/BitwiseOperators