UMBC CMSC 313 -- Multiplication/Division Program  


mul.asm


;; This section is for defining constants, such as filenames or buffer sizes,
;; It includes the initialized variables
	
section .data
miles   DW	180
gallons DW	6
mpg     DW	0
nrDays  DB	141
weeks   DB	0
days    DB	0
string1 DB	'mpg is %d', 10,0
string2 DB  'Second try is %d', 10, 0
string3 DB	'The number of hours in a week is %d', 10, 0
bigNum  DD	0


;; This section is where you declare your uninitialized variables.
section .bss

;; This is where the actual assembly code is written. 
section .text
    global  main                       ;must be declared for linker (ld)
    extern  printf
main:                                 ;tell linker entry point

;; put your code here

    mov     ax, word [miles]
    cwd                      ;ax is assumed
    idiv    word [gallons]   ;ax is assumed
    mov     [mpg], ax

    mov     eax, 0
    mov     ax, [mpg]
    push    eax
    push    string1
    call    printf
    add     esp, 8

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; DANGER: What happens with the registers when you call
;;         another function?  
;;
;;	   Let's look at it.  Repeat the pushes and call
;;         printf again!
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

    push    eax
    push    string2
    call    printf
    add     esp, 8
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Something changed ax!
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

    mov     al, [nrDays]
    sub     ah, ah        ;don't sign extend because that 
                          ;  would change the value
    mov     bl, 7
    div     bl            ;can't use a constant here!
    mov     [weeks], al
    mov     [days], ah    ;the remainder is the portion 

;
; One more example, this time with multiplication of a unsigned number
;
    mov     eax, 24       ; there are 24 hours in a day, however we need to clear all the
                          ; bits for output.
    mov     bx, 7         ; How many hours in a week?
    mul     bx            ; Calculate the answer
    push    eax           ; I know that 7 x 24 is less than +32767, so this will work.
                          ; Would not work otherwise
    push    string3
    call    printf
    add     esp, 8

;; The final part of the program must be a call to the operating system to exit
;;; the program.
    mov     ebx,0         ;successful termination of program
    mov     eax,1         ;system call number (sys_exit)
    int     0x80          ;call kernel

;; Notice the file just ends.


©2004, Gary L. Burt