Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 40 ยท Core Instructions

Arithmetic: ADD, SUB, MUL, DIV

Learn x86-64 arithmetic: add, sub, inc, dec, neg, imul, mul and div with rdx:rax, how carry and borrow work, and adc/sbb for numbers wider than a register.

Addition and subtraction on a CPU are simple, and also quietly different from what you do on paper. A register holds a fixed number of bits, so results can overflow; the processor reports what happened through the flags instead of throwing an exception. Multiplication produces a result twice as wide as its inputs, and division produces two results at once (quotient and remainder). The instructions reflect all of that.

This lesson goes through add, sub, inc, dec, neg, the three families of multiply (imul and mul), div and idiv, and the carry-chaining pair adc and sbb, which lets you add numbers larger than a register. Everything runs in toy interpreters so you can see the flags change. The flags themselves get their own deep dive in Flags and Conditions, so here we only need the four basic ones: CF, ZF, SF and OF.

add and sub

NASM
add rax, rbx        ; rax = rax + rbx
add dword [rdi], 5  ; memory += 5
sub rax, 1          ; rax = rax - 1

Both take the same operand forms as mov (register, memory or immediate; at most one memory operand) and both update the flags:

  • ZF (zero) is 1 if the result is all zeros.
  • SF (sign) is a copy of the result's top bit.
  • CF (carry) is 1 if an unsigned result did not fit: for add, there was a carry out of the top bit; for sub, a borrow happened, meaning the first operand was smaller than the second when read as unsigned.
  • OF (overflow) is 1 if a signed result did not fit: two positives gave a negative, or two negatives gave a positive.

The key insight is that the CPU does not know whether your numbers are signed or unsigned. It runs the very same addition and sets both CF and OF; you decide which flag matters by choosing a signed or unsigned conditional jump later. Adding 0xFF and 1 in 8 bits yields 0x00 with CF=1 (unsigned overflow, 255+1 wrapped) but OF=0 (signed: -1 + 1 = 0 is perfectly fine).

The toy below does 8-bit add and sub and prints the flags for several interesting cases.

JS add and sub flags on 8-bit values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Study a few rows. 100 + 100 gives 200 unsigned (no carry, CF=0), but as signed numbers it is -56: OF=1 flags that two positive numbers produced a "negative" result. 255 + 1 wraps to 0 and sets CF, ZF but not OF. And 128 - 1 is -128 - 1 as signed: the true answer -129 does not fit, so OF=1.

inc, dec and neg

inc x adds 1, dec x subtracts 1 and neg x computes the two's complement negation (0 - x). inc and dec update ZF, SF and OF but leave CF untouched, which is historically useful in multi-word loops, and also a trap if you expected CF to change. neg sets CF to 1 for every non-zero operand (it is 0 - x and a borrow happens), and OF when the operand is the most negative value (negating -128 in 8 bits gives -128 again, since +128 does not exist).

Modern compilers often prefer add rax, 1 over inc rax on some Intel microarchitectures because of the partial-flag behaviour, but you will see both.

Multiplication: imul and mul

Multiplying two n-bit numbers can need 2n bits. x86-64 provides several forms.

  • imul r, r/m (two operands): dst = dst * src, signed, result truncated to the register width. This is what compilers emit for ordinary C a * b. Since the low half of a product is identical for signed and unsigned operands, it is correct for both.
  • imul r, r/m, imm (three operands): dst = src * constant.
  • imul r/m (one operand) and mul r/m: the full-width product, signed and unsigned respectively. With 64-bit operands the result is a 128-bit number: the high 64 bits go to rdx and the low 64 bits to rax, written rdx:rax.
NASM
mov rax, 0xFFFFFFFFFFFFFFFF
mov rcx, 2
mul rcx            ; rdx:rax = rax * rcx  ->  rdx = 1, rax = 0xFFFFFFFFFFFFFFFE

mul and the one-operand imul set CF and OF when the upper half is not just the extension of the lower half (that is, when the result does not fit in the lower half alone). The other flags are undefined afterwards: do not test them.

Division: div and idiv

Division reverses that. div r/m (unsigned) divides the double-width number rdx:rax by the operand and produces two results:

  • quotient in rax,
  • remainder in rdx.

So before an unsigned 64-bit divide you must clear rdx (typically xor edx, edx). For signed division with idiv you must sign-extend rax into rdx first, using cqo (64-bit), cdq (32-bit, edx:eax) or cwd (16-bit). Forgetting this step is a classic bug: leaving garbage in rdx gives a wrong result or a crash.

The CPU raises a divide error (#DE, which Linux turns into a SIGFPE crash) in two cases: the divisor is zero, or the quotient does not fit in rax. Overflow can surprise people: idiv of the most negative number by -1 has quotient +2^63, which does not fit, so it crashes just like a divide by zero. Division is also the slowest common integer instruction, so compilers replace division by a constant with a multiply and shifts.

JS mul and div with rdx:rax

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second div fails because the dividend 5:0 (5 * 2^64) divided by 2 is 2.5 * 2^64, which does not fit in a 64-bit rax. This is why the standard idiom clears rdx first: with rdx = 0 the quotient can never exceed the dividend.

Numbers bigger than a register: adc and sbb

How do you add two 128-bit numbers on a 64-bit CPU? You add the low halves, and if that produced a carry (CF=1) you also add 1 to the sum of the high halves. The instruction adc dst, src ("add with carry") computes dst + src + CF, and sbb ("subtract with borrow") does dst - src - CF. Chained together they handle numbers of any length:

NASM
; 128-bit add: (rdx:rax) += (rcx:rbx)
add rax, rbx       ; low halves, sets CF
adc rdx, rcx       ; high halves plus the carry
flowchart LR
  L["low limbs: add"] -->|"CF"| M["next limbs: adc"] -->|"CF"| H["top limbs: adc"] -->|"CF=1 means the result overflowed"| X["final carry"]

Each adc consumes the carry produced by the step before it, like carrying a 1 in column addition.

This is exactly how big-integer libraries add. The demo below works on four 32-bit "limbs" (to keep numbers small), adds two 128-bit values using the add then adc pattern, and compares the answer against JavaScript's BigInt.

JS 128-bit addition with an add / adc chain

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Watch the carry travel: limb 0 produces 0xFFFFFFFF + 1, which wraps to 0 and carries into limb 1; limb 1 is 0 + 0 + 1; limb 2 is 0xFFFFFFFF + 1, carries again. The same pattern, with 64-bit limbs, is how multi-precision libraries and cryptographic code add and subtract.

Common mistakes

  • Using div without clearing rdx. Always xor edx, edx for unsigned, cqo for signed.
  • Testing the wrong flag. After an unsigned computation test CF; after a signed one test OF (and SF).
  • Assuming inc changes CF. It does not.
  • Reading flags after mul/div. Most of them are undefined.
  • Dividing the most negative signed number by -1. The quotient does not fit, and the CPU faults.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In 8 bits, what are the result and flags of 0xFF + 0x01?

    The result wraps to 0, so ZF=1, and there was a carry out of the top bit (CF=1). As signed numbers it is -1 + 1 = 0, which is fine, so OF=0.
  2. 2. Where does mul rcx leave the high 64 bits of the 128-bit product?

    mul and one-operand imul always produce the double-width product in rdx:rax, with the high half in rdx and the low half in rax.
  3. 3. What must you do to rdx before an unsigned 64-bit div rcx?

    div divides the 128-bit value rdx:rax. Garbage in rdx either gives a wrong quotient or triggers a divide error when the quotient does not fit.
  4. 4. How do you add two 128-bit numbers stored in register pairs?

    The first add may produce a carry. adc adds the high halves plus that carry, so the carry propagates exactly like in written addition.
  5. 5. After sub eax, ebx with eax = 3 and ebx = 5, which flag shows an unsigned borrow?

    3 - 5 is negative as unsigned, so CF=1 (borrow). SF is also 1 here, but SF is not the unsigned flag.

Summary

  • add, sub, inc, dec and neg update flags: CF reports unsigned overflow/borrow, OF reports signed overflow, ZF and SF describe the result; inc and dec leave CF alone.
  • The CPU never knows if data is signed or unsigned; you choose by which flag (or conditional jump) you use.
  • Two-operand imul is the everyday multiply; mul and one-operand imul give a 128-bit product in rdx:rax.
  • div and idiv divide rdx:rax, return the quotient in rax and the remainder in rdx, and fault on zero or overflow; prepare rdx with xor edx, edx or cqo.
  • adc and sbb fold the carry flag into the next limb, enabling arbitrary-size arithmetic.

Next: Logic, Shifts and Bit Tricks.