0

In c ~ is 1's complement operator. This is equivalent to: ~a = -b + 1 So, a - ~b -1 = a-(-b + 1) + 1 = a + b – 1 + 1 = a + b

Can anyone explains this to me?

lethal-guitar
  • 4,438
  • 1
  • 20
  • 40
  • 1
    Using a - -b is another way. – Bathsheba Mar 29 '14 at 18:50
  • This will only make sense after you understand [two's complement numbers](http://en.wikipedia.org/wiki/Two's_complement). – user3386109 Mar 29 '14 at 18:50
  • Related: http://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-work/791340#791340 – anatolyg Mar 29 '14 at 18:50
  • The steps taken by that derivation are a bit odd. `a - ~b -1 = a-(-b + 1) + 1` is valid (and equals `a + b`), but it doesn't really make sense as a step. It looks sort of like it's substituting `~b = -b + 1` (which is incorrect) and sort of accidentally fixing it by changing the subtraction at the end to an addition. Very weird. – harold Mar 29 '14 at 19:07

2 Answers2

4

From elementary school math we know

a = -(-a);

From twos complement we know that

-a = (~a) + 1  (invert and add one)

so we know that

a + b 
= a - (-b)      elementary math
= a - (~b + 1)  twos complement
= a - (~b) - 1   distribute the negative (elementary math)
old_timer
  • 69,149
  • 8
  • 89
  • 168
0

You are right that ~ is always 1's complement (aka bitwise not) in c. Where you are going wrong is this: C does not guarantee 2's complement for numbers. So all your calculations depend on using a major flavor of C.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118