Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding negative and positive binary?

Tags:

math

binary

X = 01001001 and Y = 10101010

If I want to add them together how do I do that? They are "Two's Complement"... I have tried a lots of things but I am not quite sure I am getting the right answer since there seems to be different type of rules.

Just want to make sure it is correct:
1. Add them as they are do not convert the negative
2. Convert the negative number you get and that's the sum.

f.eks
01001001+10101010 = 11110011 => 00001100 => 1101 => -13

Or?
1. Convert the negative
2. Add them together and convert the negative

f.eks
01001001+10101010 => 01001001 + 01010110 => 10011111 => 01100001 => -97


So basically what I want to do is to take: X-Y, and X+Y
Can someone tell me how to do that?

Some resource sites: student-binary celtickane swarthmore

like image 301
suxSx Avatar asked Dec 06 '08 21:12

suxSx


1 Answers

The beauty of two's complement is that at the binary level it's a matter of interpretation rather than algorithm - the hardware for adding two signed numbers is the same as for unsigned numbers (ignoring flag bits).

Your first example - "just add them" - is exactly the right answer. Your example numbers

  • 01001001 = 73
  • 10101010 = -86

So, the correct answer is indeed -13.

Subtracting is just the same, in that no special processing is required for two's complement numbers: you "just subtract them".

Note that where things get interesting is the handling of overflow/underflow bits. You can't represent the result of 73 - (-86) as an 8-bit two's complement number...

like image 152
Roddy Avatar answered Dec 02 '22 20:12

Roddy