I'm getting started in Python programming. I'm reading a basic tutorial, but this point is not very clear to me. I would appreciate any help you can give me.
-
5This has nothing to do with pyton but with how negative numbers are represented in binary (see wikipedia/google for 2's complement). – Oct 12 '10 at 16:14
-
@skaffman: *This has nothing to do with python* – SilentGhost Oct 12 '10 at 16:28
-
@skaffman: title is just fine – SilentGhost Oct 12 '10 at 17:08
-
1Does every language use the ~ operator? If not, then I don't see why the Python tag is bad. – AHungerArtist Oct 12 '10 at 17:12
5 Answers
~3 means 'invert' 3. With two's complement on natural number datatypes, this becomes -4, as the binary representation is inverted (all bits are flipped).

- 22,412
- 8
- 58
- 84
-
2Just to show it in hex:3 = 0x00000003 ~3 = 0xFFFFFFFC and the numbers are signed therefore it is negative. – Vinzenz Oct 12 '10 at 16:14
Because signed integers are usually stored using two's complement, which means that the bitwise inverse of an integer is equal to its algebraic inverse minus one.

- 342,105
- 78
- 482
- 720
~3 means "change all the 1s to 0s and 0s to 1s", so if 3 in binary is 0000000000000011, then ~3 is 1111111111111100. since the first bit of ~3 is a 1, its a negative number. to find out which negative number, in 2s comliment, you invert all bits and add 1, so inverted we are back to 3, then added 1 we get 4.
It's the invert operator, and returns the bitwise inverse of the number you give it.

- 4,716
- 3
- 30
- 50
It's not just Python, it's the integer numeric representation of almost all modern computers: two's complement. By the definition of two's complement, you get a negative number by complementing the positive number and adding one. In your example, you complemented with ~
but did not add one, so you got the negative of your number minus one.

- 299,747
- 42
- 398
- 622