tags:

views:

83

answers:

5

If a large number is subtracted from a smaller number then borrow is needed. The carry flag plays the role of borrow during the subtraction operation. Now suppose we want to subtract 56 from 66, obviously the borrow is needed and carry flag will be set. Now how this subtraction is performed to get the result -10, how computer will distinguish that the result is going to be a negative number. Please explain the process.

A: 

Computer will not distinguish this. Computer doesn't care about sign, you and compiler do. You will store this value into signed variable and then use it as signed. There is no semantic difference between long numbers and negative numbers.

Andrey
+2  A: 

The computer doesn't need to, if it's using 2's complement.

Let's consider a simpler example, 3 - 5:

    0011 = 3
-   0101 = 5
————————
    1110 = 14

The result is 14, but in 2's complement, this is also the value of -2. So, if the code uses signed type, it will correctly get -2. Otherwise, it will get 14. It all depends on how the programmer write the code.

KennyTM
+1  A: 

Computer does not do a subtraction. It does the addition of a negative number.

So, 56 - 66 = 56 + ( -66 )

56 = 0x38 ( 38 in hexadecimal )

-66 = 0xFFFFFFBE ( complement of 0x42 in a 32-bit system )

If you do would add these hex numbers you will end up with 0xFFFFFFF6, which is a negative complement of 0xA, which is a decimal 10.

Alexander Pogrebnyak
+2  A: 

Normally, subtraction is implemented as a negate, then add. So for your example, the CPU would internally take 56 and add -66. On an x86 (or most other modern processors) the negate will be done with two's complement, which means negate translates to "complement all the bits, then add one (and ignore any carry out)."

    0011 1000
-   0100 0010
    ---------

The second operand is transformed as follows:

complement bits: 1011 1101
Increment:       1011 1110

So the operation that's carried out is:

    0011 1000
+   1011 1110
--------------
=   1111 0110

This result can be viewed as either 246 (as an unsigned number) or -10 (as a signed number).

Jerry Coffin
A: 

The carry flag is not the same as a sign bit. The carry flag is used to do multi-part arithmetic, where the result of one addition or subtraction needs to affect the next higher part.

With the increase in register sizes over the years and the waning of assmbler, you don't see this done much anymore.

Mark Ransom