CSC231 FibOverflowByte.asm

From dftwiki3
Jump to: navigation, search
;;; fibOverflowByte.asm
;;; D. Thiebaut
;;; Computes fibonacci[i] until overflow (number becomes negative)
;;; Requires driver.c, asm_io.o, and asm_io.inc
;;; 
;;; Compile and link as follows:
;;;
;;;  nasm -f elf -F stabs factorial.asm
;;;  gcc -o factorial driver.c asm_io.o factorial.o
;;; 
%include "asm_io.inc"
        
%assign EXIT        1

        ;; -------------------------
        ;; data segment
        ;; -------------------------
        section .data
msg1    db      "fib(",0
msg2    db      ") = ",0


        section .bss
N       equ     100        
fib     resb    N               ; reserve 100 bytes
        
        ;; -------------------------
        ;; code area
        ;; -------------------------
        section .text
        global  asm_main

;;; ---------------------------------------------------------
;;; main program
;;; ---------------------------------------------------------
asm_main:       

;;; fib[0] = 1;
;;; fib[1] = 1;
;;; for ( i=2; i<100; i++ ) {
;;;     temp = fib[i-1]+fib[i-2];
;;;     if ( temp <= 0 ) break;
;;;     fib[i] = temp;
;;; }
        mov     byte[fib], 1
        mov     byte[fib+1], 1

        mov     esi, 2          ; esi is i
for:    cmp     esi, N
        jge     done
        
        mov     al, byte[fib+esi-1]
        add     al, byte[fib+esi-2]
        cmp     al, 0
        jle     done
        mov     byte[fib+esi], al
        call    printFibi
        inc     esi
        jmp     for
        
done:   ret        
        
;;;     print "fact( %d ) = %d" % (i, fact(i) )
        
printFibi:      
        and     eax, 0x000000ff ; keep al, clear the rest
        push    eax             ; save fib(i) in stack
        push    esi             ; save i in stack
        mov     eax, msg1        
        call    print_string    ; prints "fib( "

        pop     eax             ; get esi in eax
        call    print_int       ; print i

        mov     eax, msg2       ; print ") = "
        call    print_string
        
        pop     eax             ; get fib(i) back from stack
        call    print_int       ; print fact(i)

        call    print_nl        ; next line
        ret