HOME Acknowledgement Chapter 1 - Basics of Computer Organization Chapter 2 - Introduction to NASM Chapter 3 - Basic I/O in NASM Chapter 4 - Introduction to Programming in NASM Chapter 5 - Integer Handling Chapter 6 - Subprograms Chapter 7 - Arrays and Strings Chapter 8 - Floating Point Operations
National Institute of Technology, Calicut Creative Commons License

NASM Manual NITC

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.

  1. Declaring an integer

  2. Here we have reserved 10 bytes/words/double words for the memory location 'var'
  3. Reading a single digit

  4. 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].
  5. Reading a multi-digit number

  6. 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:
  7. Printing a number

  8. 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: