0

I am reading "Chapter 13: Operator Overloading: Doing it Right",
It states Unary Operators

~ (__invert__) Bitwise inverse of an integer, defined as ~x == -(x+1). If x is 2 then ~x == -3.

I am very confused here. How could it be that if x is 2 then ~x == -3 ?

Could you please provide any hints?

khelwood
  • 55,782
  • 14
  • 81
  • 108
AbstProcDo
  • 19,953
  • 19
  • 81
  • 138
  • 2
    See [What is 2's complement?](https://stackoverflow.com/questions/1049722/what-is-2s-complement) – khelwood Sep 19 '18 at 10:16
  • Start by understanding how computers store numbers, and especially how this works for *negative* numbers. Once you understand how that works, take both a positive and a negative integer number, and write out their binary representations. Write down all the zeros and ones. Then, write out their inverse, flip the 1s for 0s and the 0s for 1s, and work out the integer value (so go the other direction). See what happened there? – Martijn Pieters Sep 19 '18 at 10:27

1 Answers1

1

The binary representation of the decimal value 2 is 0010. Bitwise inversion means turning all 0s to 1s and all 1s to 0s, resulting in 1101. Read into the Two's Complement to find out why this represents a decimal value of -3.