0

I did:

79_10 = 1001111

42_2 = 101010

I took 2's Complement of 42 and got 010110. Then I did 1001111 + 010110 and got 1100101 but this is 101. If I remove the leftmost one it becomes 37 which is correct... where did it go wrong?

2 Answers2

2

When doing 2's complement, you have to decide beforehand exactly how many bits you have, and then use that many bits, nothing more, nothing less, for any number in your calculation.

To be able to calculate with $79$, you need at least $8$ bits. So let's go for $8$ bits. Then $$ 79_{10} = 01001111_2\\ 42_{10} = 00101010_2 $$ So with $2$'s complement, we get $$ -42_{10} = 11010110_2 $$ Now we can add the two to get $$ \begin{array}{cc} &01001111\\ +&11010110\\ \hline=&00100111 \end{array} $$ with a carry that disappears. So the end result is $$ 00100111_2 = 37_{10} $$ as expected.

Arthur
  • 199,419
  • Why 8 bits and not 7? – SilenceOnTheWire Oct 09 '19 at 14:04
  • Why? I don't get it – SilenceOnTheWire Oct 09 '19 at 14:06
  • @SilenceOnTheWire Because there are only $128$ different numbers you can write with $7$ bits, and we want (roughly) half of them to be negative (because why else do $2$'s complement?) That limits us to numbers below $64$. – Arthur Oct 09 '19 at 14:08
  • @SilenceOnTheWire Equivalently, you need at least $7$ bits because you're going over $63$ (the seventh bit is worth $64$, and we need that if we want to describe $79$). Then we have an eighth bit for sign, because we want to have the capacity to do negative numbers as well. Regardless of reasoning, the fact still stands: you need at least 8 bits. – Arthur Oct 09 '19 at 14:10
0

Let us make the computations in a parallel manner, bases ten and two: $$ \begin{aligned} &79-42 \\ &= 79+(64-42)-64 \\ &=79+22-64 \\ &=101-64 \\ &=37\ . \end{aligned} \qquad \begin{aligned} &1001111-101010 \\ &=1001111+010110-1000000 \\ &=1100101-1000000 \\ &=100101\ . \end{aligned} $$

dan_fulea
  • 32,856
  • Where does the 64 come from? – SilenceOnTheWire Oct 09 '19 at 14:07
  • It corresponds to the "bit inversion". Note that exchanging $-42$ in something positive as in the OP does introduce this $64$. What is $64-42$ in base two? This inserts a relevant bit in the place where the contribution comes from $64$. The question is "Where did i go wrong?!" an the answer is at this place, where the $64$ was neglected. Just consider the computation in base ten "as it is", the the computation in base two as a reflection, and then the place where $64$ is omitted. – dan_fulea Oct 09 '19 at 14:11