binary - Adding and subtracting two's complement -
using six-bit one's , two's complement representation trying solve following problem:
12 - 7
now, take 12 in binary , 7 in binary first.
12 = 001100 - 6 bit 7 = 000111 - 6 bit
then, flip bit two's complement , add one?
12 = 110011 ones complement + 1 ------- 001101 7 = 111000 ones complement + 1 --------- 111001
then, add 2 complement together
001101 +111001 ------- 1000110 = overflow? discard last digit? if 5
now, if have number like
-15 + 2
i add sign magnitude on msb if it's zero?
like:
-15 = 001111 6 bit
would add 1 @ end here before flip bits?
= 101111
using two's complement represent negative values has benefit subtraction , addition same. in case, can think of 12 - 7
12 + (-7)
. hence need find two's complement representation of -7 , add +12:
12 001100 -7 111001 -- this, invert bits of 7 (000111) , add 1 ---------- 5 1000101
then discard carry (indicates overflow), , have result: 000101
equals 5 expected.
for example of -15 + 2
, follow same procedure two's complement representation of -15:
15 001111 110000 -- inverted bits 110001 -- add 1
now addition usual:
-15 110001 2 000010 ----------- res 110011
to see res
indeed equals -13, can see negative (msb set). magnitude, convert positive (invert bits, add 1):
res 110011 001100 -- inverted bits 001101 -- add 1
hence magnitude 13 expected.
Comments
Post a Comment