I am trying the following code and here are the outputs, anyone have ideas why -10 and -11 are returned?
print ~9
print ~10
-10
-11
BTW, I am using Python 2.7.8.
I am trying the following code and here are the outputs, anyone have ideas why -10 and -11 are returned?
print ~9
print ~10
-10
-11
BTW, I am using Python 2.7.8.
From: Python Doc
The unary ~ (invert) operator yields the bitwise inversion of its plain or long integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers.
From: Python Doc
Two's Complement binary for Negative Integers:
Negative numbers are written with a leading one instead of a leading zero. So if you are using only 8 bits for your twos-complement numbers, then you treat patterns from "00000000" to "01111111" as the whole numbers from 0 to 127, and reserve "1xxxxxxx" for writing negative numbers. A negative number, -x, is written using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1). So -1 is complement(1 - 1) = complement(0) = "11111111", and -10 is complement(10 - 1) = complement(9) = complement("00001001") = "11110110". This means that negative numbers go all the way down to -128 ("10000000").
~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.