Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CMP (compare) sometimes sets a Carry Flag in 8086 assembly?

I've been reading around and with the 8086 Instruction Set, it says that a CMP (compare) can set the Carry Flag. I understand that a compare subtracts two operands but I was wondering if anyone can provide an example when that is the case.

I just can't grasp the idea of adding a number and a negative number will set the carry flag. I've read into the borrow flag but I just needed an example to clarify my understanding of a compare instruction.

Also, I understand that if 3 - 5 = -2 would set the negative flag... when is carry set?

like image 451
faul Avatar asked Nov 07 '11 00:11

faul


People also ask

Does CMP change carry flag?

CMP and TEST instructions affect flags only and do not store a result (these instruction are used to make decisions during program execution). These instructions affect these flags only: CF, ZF, SF, OF, PF, AF.

How flags are affected by CMP instruction?

The CMP instruction sets the flags as if it had performed subtraction on the operand. Subtracting 1000 from 1000 results in zero. A conditional jump instruction branches to a destination label when a flag condition is true.

What does CMP do in assembly?

The CMP instruction compares two operands. It is generally used in conditional execution. This instruction basically subtracts one operand from the other for comparing whether the operands are equal or not.

What does CMP return in 8086?

- The CMP instruction can be used to compare two 8-bit or two 16-bit numbers. - Whenever a compare operation is performed the result of such an operation reflects in one of the six status flags CF, AF, OF, PF, SF and ZF. -The CMP operation is also known as the subtraction method as it uses two`s complement for it.


1 Answers

  • The carry flag is set after an operation that resulted in an underflow or overflow. For example, subtracting 10 from 6 will result in an underflow and set the carry flag. Similarly, adding 1 to the maximum value of the register will result in an overflow and set the carry flag.
  • The carry flag is also modified during a shift operation, it is set to the value of the last bit shifted out of the destination register.
  • Bit testing will place the value of the tested bit into the carry flag. Opcodes that do this: BT, BTC, BTR, and BTS.
  • Instructions that affect the Carry Flag directly: CLC, CMC, and STC.
  • During a comparison, the carry flag is set just as if the two operands had been subtracted.
  • During a negation (NEG), the carry flag is set unless the operand is zero, in which case it is cleared.
like image 66
Sparafusile Avatar answered Nov 08 '22 03:11

Sparafusile