-2

I have a question in my programming class, it is: What is the value of ~12 and the answer is -13. I don't understand why? I convert 13 base 10 to binary, which is 1100, than I switched all the 1 for 0 and vice versa, it gives me 0011, so I thought the answer was 3 but it's not.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
minos01
  • 19
  • So what is 13 expressed in binary again? – quamrana Sep 26 '21 at 21:33
  • What operation is `~`? – esqew Sep 26 '21 at 21:34
  • 3
    There are an infinite number of 0 bits on the left side. – o11c Sep 26 '21 at 21:40
  • You can see a practical use of this in my answer to a mostly-unrelated question here: https://stackoverflow.com/a/63552117/1405588 – o11c Sep 26 '21 at 21:41
  • @esqew Are you asking for the name, or what do you mean? – no comment Sep 26 '21 at 21:42
  • @don'ttalkjustcode I’m simply trying to understand what mathematical operation is denoted using the tilde `~` as I’m personally unfamiliar with the symbol being used in this way and a cursory search turned up no relevant results. – esqew Sep 26 '21 at 21:44
  • @esqew Just look up all the operators in python. – quamrana Sep 26 '21 at 21:45
  • Your question says that you *"switched all the 1 for 0 and vice versa"*, so it appears you do indeed understand exactly what `~` does, the issue is that you didn't realise there are infinitely many `0` bits to the left of `1100` which also have to be switched to `1`. Please see the questions I linked to for an explanation of this. – kaya3 Sep 26 '21 at 21:48
  • Negative integers are represented using two's complement in binary. That's why inverting the bits gives that absolute value plus 1. For more info: https://en.wikipedia.org/wiki/Two%27s_complement – Alain T. Sep 26 '21 at 22:37

1 Answers1

3

Converting 12 to a signed binary number yields 01100 then assuming that ~ is supposed to invert every bit we get 10011 which can be converted from signed binary to decimal yielding -13.

Essam
  • 395
  • 3
  • 15
  • How do you know that when you convert it, it has to be on 5 bits? – minos01 Sep 26 '21 at 21:56
  • To know whether a signed binary number is positive or not you look at the first digit. If it's 0 it's positive and if it's 1 it's negative. Because we know that the original number is +12 we have to start the number with at least one zero in the binary representation. I suggest that you read more about signed binary numbers. – Essam Sep 26 '21 at 22:36