I am currently learning about Python bitwise operators at Code Academy and got to the ~
operator, which is explained to turn all the 0s into 1s and all the 1s into 0s. It is also explained that the result of this is your number basically being multiplied by -1 and then decremented by 1. Code Academy says that the math behind this is "too complicated." I found a document that adds that there is also a 1/0 that governs whether or not the number is negative, which makes a lot of sense. However, I don't see that 1/0 in my bit expression of a number. I love mathematics and would love to understand the math behind the operator. I have not been able to Google it. Anyone have any docs on the matter or could guide me in the right direction to understand this?
Asked
Active
Viewed 92 times
0

TigerhawkT3
- 48,464
- 6
- 60
- 97

dsalcovs
- 41
- 2
-
What do you mean "my bit expression of a number"? It's unclear exactly what you're asking for. – BrenBarn Aug 15 '15 at 23:03
-
1[One's complement](https://en.wikipedia.org/wiki/Ones'_complement) – Jeff Mercado Aug 15 '15 at 23:04
-
Computers generally use Two's Complement to represent signed numbers: https://en.wikipedia.org/wiki/Two%27s_complement. Basically the most significant bit has a -ve value. For a four-bit signed number, the bits would represent values 1, 2, 4, -8. So the range of numbers that could be represented is -8 to +7. – Tom Dalton Aug 15 '15 at 23:08
-
I don't think this is a duplicate at all. The OP is asking for the math behind it, which none of the answers address. The math is not "too complicated." Two's complement arithmetic is arithmetic modulo 2^N (for N-bit numbers.) If you add x and ~x, you obviously get 2^(N-1) Add 1 and you have 0 (mod 2^N). So, flipping all the bits of x and adding 1 gives -x, which is equivalent to what you read on Code Academy. – saulspatz Aug 16 '15 at 00:38
-
@saulspatz The accepted answer to the linked question mentions the mathematical identity and links to the Wikipedia article on two's complement for further information. If that doesn't answer the question, we need a more specific question for what's still unclear. – 5gon12eder Aug 16 '15 at 02:52