问题
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?
回答1:
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)
回答2:
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.
来源:https://stackoverflow.com/questions/22735305/adding-two-numbers-without-using-the-addition-operator