patternMinor
Binary 2s Compliment Applied Twice Gives Original - How?
Viewed 0 times
twiceoriginalappliedgivesbinaryhowcompliment
Problem
At the moment the maths behind binary 2s compliment seems like voodoo to me.
If I take 0011 (+3) and "flip and add 1", I get 1101 (-3)
If I apply the same process to 1101, ("flip and add 1"), I get back to the original positive value.
How is this so?
If I take 0011 (+3) and "flip and add 1", I get 1101 (-3)
If I apply the same process to 1101, ("flip and add 1"), I get back to the original positive value.
How is this so?
Solution
If we look at the numbers in an unsigned way, flipping a binary number $x$ on $n+1$ bits is computing $(2^{n+1} -1) - x = M - x$.
Proof for that: $x = \sum_0^n b_i2^i$. $x$ flipped : $\sum_0^n (1-b_i)2^i = \sum_0^n 2^i -\sum_0^n b_i2^i = (2^{n+1} - 1) - x$
Therefore, flip and add one : $y = (M - x) + 1$
Again : $z = (M - y) +1 = (M - ((M - x) + 1)) + 1$
$z = (M - (M - x) - 1) + 1$
$z = M - M + x - 1 + 1$
$z = x$
Proof for that: $x = \sum_0^n b_i2^i$. $x$ flipped : $\sum_0^n (1-b_i)2^i = \sum_0^n 2^i -\sum_0^n b_i2^i = (2^{n+1} - 1) - x$
Therefore, flip and add one : $y = (M - x) + 1$
Again : $z = (M - y) +1 = (M - ((M - x) + 1)) + 1$
$z = (M - (M - x) - 1) + 1$
$z = M - M + x - 1 + 1$
$z = x$
Context
StackExchange Computer Science Q#102383, answer score: 3
Revisions (0)
No revisions yet.