Arithmetic
ADD and SUB
ADD and SUB work like MOV: two operands of the same size, destination first. Both set the flags, so one SUB can serve as a compare:
add rax, rbx ; rax = rax + rbx sub rax, 1 ; rax = rax - 1 inc rax ; rax = rax + 1 dec rcx ; rcx = rcx - 1
MUL and IMUL
One-operand MUL multiplies RAX by the operand and stores the 128-bit result in RDX:RAX. Two- and three-operand IMUL keeps the low half and is the form compilers emit:
imul rax, rbx, 10 ; rax = rbx * 10 (three-operand) imul rax, rbx ; rax = rax * rbx (two-operand) mul rcx ; rdx:rax = rax * rcx (one-operand)
DIV and IDIV
DIV divides RDX:RAX by the operand: the quotient lands in RAX and the remainder in RDX. Clear RDX first, or the high dividend bits corrupt the result:
xor rdx, rdx ; clear the high dividend div rcx ; rax = quotient, rdx = remainder
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which instruction adds one to a register?
Answer
INC
INC adds one without a second operand; ADD takes an explicit value.
-
Where does one-operand MUL put the 128-bit result?
Answer
In RDX:RAX
The product of two 64-bit numbers can need 128 bits, so the high half goes to RDX.
-
Which IMUL form keeps only the low half of the product?
Answer
The two- and three-operand forms
Two- and three-operand IMUL write one destination and discard the high half.
-
What must you clear before DIV?
Answer
RDX
DIV divides RDX:RAX, so a stale RDX makes the dividend far too large.
-
After
div rcx, where is the remainder?Answer
RDX
The quotient lands in RAX and the remainder in RDX.
-
What does
imul rax, rbx, 10compute?Answer
rbx times 10 into rax
The three-operand form multiplies the second operand by the constant into the first.
-
What does this program print?
default rel section .data digit db "0", 10 section .text global _start _start: mov rax, 4 add rax, 3 add al, "0" mov [digit], al mov rax, 1 mov rdi, 1 mov rsi, digit mov rdx, 2 syscall mov rax, 60 xor rdi, rdi syscallAnswer
7
4 + 3 = 7, and the ASCII adjustment turns it into the digit 7.
-
What exit status does this program return?
section .text global _start _start: mov rax, 100 xor rdx, rdx mov rcx, 9 div rcx mov rdi, rax mov rax, 60 syscallAnswer
11
100 divided by 9 is 11 with a remainder of 1, and the quotient is the status.
-
Which instruction subtracts one from a register?
Answer
DEC
DEC subtracts one and sets the flags from the result.
-
What happens when the high half of a dividend is not cleared for DIV?
Answer
The quotient is wrong or the divide faults
The dividend is the full RDX:RAX pair, so garbage in RDX changes or overflows the result.
The snippets on this page are fragments, not whole programs: they show the arithmetic instructions. They were assembled with NASM 3.01 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev