Chapter 5 - Integer Handling
Integers are stored as characters in NASM. This chapter describes how to read and print integers. We have already skimmed through the basic operations in integer handling (add, sub, mul, div) in Chapter 3. Here, we will look at sample programs that will make use of these operations.
-
Declaring an integer
Here we have reserved 10 bytes/words/double words for the memory location 'var'
-
Reading a single digit
To read a single digit, we will read it as a single character and then subtract 30h from it (ASCII of 0 = 30h). This is to get the actual value of that number in that variable.
Note that the single digit taken as input here is stored in the first byte of 'var'. If 'var' was declared as a word/double word, the size of the input stored in the edx register should be changed accordingly to word[size] or dword[size].
-
Reading a multi-digit number
To read a multi-digit number, we read the input character by character (here, digit by digit) until we obtain the enter-key. Each digit is multiplied with 10 and added to the next digit to obtain the original number.
Pseudo Code:
while(temp!=enterkey)
num=0
read(temp)
num=numx10+temp
endwhile
NASM Code:
-
Printing a number
Unlike when we're reading a number, there is no end character like the enter-key marking the number's last digit. Here, we extract each digit from the number and push it to the stack. We also keep a count of the number of digits in the number. Using this count, the digits are popped out of the stack and printed in order.
Pseudo Code:
count=0
while (num!=0)
temp=num%10
count++
push(temp)
num=num/10
endwhile
while(count!=0)
temp=pop()
print(temp)
count- -
endwhile
NASM Code:
Example Program
Read 2 numbers and find their GCD.
Pseudo Code:
read(num1)
read(num2)
while(1)
if(num1%num2==0)
goto endloop
temp=num1%num2
num1=num2
num2=temp
endwhile
endloop:
print(num2)
NASM Code: