Arithmetic Instructions

(Arithmetic.nasm)

Here we will look into Addition, Subtraction, Multiplication, Division using assembly.

Also, its important to look at eFlags registers as arithmetic operation affects status flag.

Compile, load in gdb , set intel format, _start breakpoint.

hook-stop:

Addition →

Let say, I want to add two 4 digits number, 5555 and 6666, this will generate result of 12221. 12221 is a five digit number. Now same situation in registers, two 8 bit registers used for addition which could lead to a 9 bit answer. How will that be saved? In normal calculations we remember a term named ‘carry’.

Here, we are adding 0xffffffff and 0x10 leading in a result of 0x10000000f, but this is more than the capacity/range of our register. So, Carry flag(CF) is set.(Shown above)

Since we talked about carry flag, lets look a bit about flag related instructions.

A few flag related instruction→ clc, stc, cmc

clc → clear carry flag ,CF=0

stc → set carry flag ,CF=1

cmc → complementary carry flag, CF=NOT(CF)

Subtraction →

Multiplication

mul 0x5 → means eax will get multiplied with 0x5

mul ebx → means eax will get multiplied with ebx

->AL (multiplied with) r/m8 → AX (r/m8 → register/memory of 8 bit) ->AX (multiplied with) r/m16 → DX AX (r/m16 → register/memory of 16 bit)(DX contains upper half bits and AX contains lower half bits) ->EAX (multiplied with) r/m32 → EDX EAX (r/m32 → register/memory of 32 bit)(EDX contains upper half bits and EAX contains lower half bits)

Sometime the result can be more than the specified bit. In that case, OF and CF flag are set to 1

Lets define a new hook-stop, to look for EDX register changes as well.

We can check the final answer as well.(checked in python)

Division

AX (divided by) r/m8 -> Quotient in AL, Remainder in AH DX AX (divided by) r/m16 -> Quotient in AX and Remainder in DX EDX EAX (divided by) r/m32 -> Quotient in EAX and Remainder in EDX

Result stored as: Quotient in EAX register and Remainder in EDX.

💡 Lets say, we want to perform following operation: 10%3 ,i.e. modulo. In such case, everything will be same. 10 / 3 gives 3 as quotient(EAX) and 1 as remainder(EDX). So, EDX value will be showed for 10%3.

Apart from these, INC and DEC are other 2 instructions used for incrementing the value by 1 and decrementing the value by 1 respectively.

Last updated