2

When I need to subtract 2 numbers (X-Y), I can take 2's complement of Y and add it to X. Let's say our system represents integers using a byte (8 bits).

X = 7 = 00000111
Y = 5 = 00000101

2's complement of 5

11111010 + 1 = 11111011

Adding those 2 =

 00000111
 11111011
__________
100000010 

There is a carryover. How does one deal with this carryover?

If I am using 8 bits, that means I have a range of -128 to 127. So 7 and -5 and their sum do not fall outside that range. So this is not overflow.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
Quest Monger
  • 8,252
  • 11
  • 37
  • 43

2 Answers2

1

that depends on what you are trying to do

  1. if you are just computing simple/single +/- operations

    then the overflow is usually ignored

  2. when you need to handle overflow/underflow

    for example if you need to clamp the result for some reason (usually safety of the result range ...) then Carry flag of the ALU marks if the overflow underflow occur. After that you set the result as max positive or negative value depending on the inputs sign,magnitude and operation (+,-). Aome platforms have instructions that do this automatically (saturated add,sub).

    Another reason is making bigint operations in that case carry is added as +/-1 to higher operation (sign depends on the operation)... but the result itself stays as is (add,adc,adc,adc,...)

  3. on modern languages/platforms you do not have direct ALU flag register access anymore

    sometimes you can tap into assembler but it can be slower in some cases then the computation itself. In that case use this approach 32bit ALU in C++ where cy is the carry flag

Spektre
  • 49,595
  • 11
  • 110
  • 380
0

Should have read my textbook again :)

In 2's complement arithmetic the carryover is thrown away, versus 1's complement arithmetic, where carryover is carried back and added to the result.

This video helped me understand - https://www.youtube.com/watch?v=lKTsv6iVxV4

Quest Monger
  • 8,252
  • 11
  • 37
  • 43