3
$\begingroup$

In college, we've seen some general formulas to compute the decimal value a of a binary representation $a_{N-1} \dots a_2 a_1 a_0$ in two's complement, $N$ being the number of bits. For $a \ge 0$ we've seen $a= \sum_{i=0}^{N-2} a_i 2^i$, which seems correct to me if I work it out. But for $a < 0$ our book says $a=-2^{N-1}+\sum_{i=0}^{N-2} a_i 2^i$ and this is where I go wrong.

Can someone explain with an example why this is correct or which formula is right?

$\endgroup$

1 Answer 1

4
$\begingroup$

Let $a_{N-1} \cdots a_0$ be the two's complement representation of the number $a$. The more general formula is: $$a = -a_{N-1}2^{N-1} + \sum_{i=0}^{N-2} a_i 2^i$$ (I am sure you can figure out how your formulas can be derived from this one.)

Why does this hold? For $a \ge 0$, $a_{N - 1} = 0$ and then the value of $a$ is simply the value of the binary representation $a_{N-2} \cdots a_0$. For $a < 0$, on the other hand, let $b = -a \ge 0$ have binary representation $b_{N-1} \cdots b_0$. Then $$\sum_{i=0}^{N-1} a_i 2^i = \sum_{i=0}^{N-1} (1-b_i) 2^i + 1 = \sum_{i=0}^{N-1} 2^i - \sum_{i=0}^{N-1} b_i 2^i + 1 = 2^N - b$$ since the two's complement is defined as the complement of the representation $b_{N-1} \cdots b_0$, plus one, and $\sum_{i=0}^{N-1}2^i = 2^N - 1$. Since $a$ is negative, $a_{N-1} = 1$ and then: $$a = -b = -2^N + \sum_{i=0}^{N-1} a_i 2^i = -2^N + 2^{N-1} + \sum_{i=0}^{N-2} a_i 2^i = -2^{N-1} + \sum_{i=0}^{N-2} a_i 2^i $$


I have refrained from giving an explicit example as you had asked; I believe explaining why the formula works in the first place is far more instructive.

$\endgroup$
3
  • $\begingroup$ Thanks a lot! This makes it very clear. I also see know there's a mistake in the general formule for a. Instead of a(N-1), our book said a(N) and the professor noted there may be a mistake in it, but didn't say what it was. You explained it very well! $\endgroup$
    – L3k
    Dec 6, 2018 at 12:43
  • $\begingroup$ @L3k If you believe this a satisfactory answer to your question, don't forget to click the tick mark to the left and mark it as an "accepted" answer ;) $\endgroup$
    – dkaeae
    Dec 6, 2018 at 14:01
  • $\begingroup$ I've only just now started to us this, so thanks a lot for the tip :) @dkaeae $\endgroup$
    – L3k
    Dec 29, 2018 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.