0

I'm learning a computer architecture course.

My teacher told me that signed integers are stored in two's complement, and that when doing subtraction, for example, x - y, the complement of y is added to x.

This course also teaches some assembly language. I learned that the carry flag is set after an operation if the operation generates a carry or a borrow out of the most significant bit of the result.

Given the above knowledge, I am confused by the result of the following examples:

example1:
; eax = C2h, ecx = 22h
sub eax, ecx 
; after this, cf = 0

example2:
; eax = 22h, ecx = C2h
sub eax, ecx
; after this, cf = 1

The first example is to calculate

C2 - 22 =
C2 + (FFFFFFDE) =
C0 + overflowed 2^32 carried out of the most significant bit

, for which I think that cf should be set

And the second example is to calculate

22 - C2 =
22 + FFFFFF3E =
FFFFFF60 with no overflow, so no carry out of the most significant bit

, for which I think that cf should not be set

Why the actual result turned out to be the very contrary? Did I misunderstand something?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Guanyuming He
  • 167
  • 10
  • 2
    On x86, CF is a "borrow" output from subtraction. (Fun fact: opposite of ARM where it's a !borrow flag). It matters how you get there, and it's *not* equivalent to turning it into addition like `neg` / `add`. See [Arithmetic identities and EFLAGS](https://stackoverflow.com/a/62219965) – Peter Cordes Nov 16 '21 at 11:53
  • To add to what Peter said, you can always use a `cmc` instruction to flip the carry flag. – fuz Nov 16 '21 at 11:57
  • @PeterCordes -are there any currently made processors that use subtract logic instead of complement and add logic? – rcgldr Nov 16 '21 at 17:20
  • @rcgldr: No idea. Probably not, though. – Peter Cordes Nov 16 '21 at 23:46

0 Answers0