Monday, March 14, 2016

8086 Assembly Even Odd Checking Code Explanation Line by Line


Instruction:

Compile and run the code in emu8086 for easier usage. Input is any number from 0-9.

Code without Loop:

;Author:quickgrid
;Site: http://quickgrid.blogspot.com
;Code: Even odd check 8086 assembly code
;predefined macro for speed coding
;define any code here that is reduandant
newline macro
lea dx,nl
mov ah,9
int 21h
endm
.model small
.stack 100h
.data
;remermber to put a $ after or if you want it
;keep executing than put it on other line
msg1 db 'number is even', '$'
msg2 db 'number is odd', '$'
nl db 0dh,0ah, '$'
.code
.startup
;initialize data segment
mov ax,@data
mov ds,ax
;ah=1 is take input, int 21h execute above command
mov ah,1
int 21h
;divide al by whatever is in bl
mov bl,2
div bl
;ah contains remainder after division, al contains the operand, no need for
;operand anymore replace with remainder
mov al,ah
;check if remainder is zero
cmp al,0
;use any condition here jump greater, jump if not equal etc
jg odd
;if it was a odd number than it would never reach here
;print a new line if even
even:
newline
;print the string in msg1 and skip rest of the code to exit label
lea dx,msg1
mov ah,9
int 21h
jmp exit
;the previous jg odd label jumps to here skipping even portion of the code
odd:
newline
;show the message for odd number
lea dx,msg2
mov ah,9
int 21h
;just a jump label to skip executing some codes
exit:
.exit


Code with Loop:

;Author:quickgrid
;Site: http://quickgrid.blogspot.com
;Code: Even odd check using loop in 8086 assembly explained code
.model small
.stack 100h
.data
msg1 db ': odd$'
msg2 db ': even$'
.code
main proc
mov ax, @data
mov ds, ax
;when loop called it uses cx as counter
mov cx, 9
;loop label
looper:
;input a number
mov ah, 1
int 21h
;divide any number in al by bl or 2 here
mov bl, 2
div bl
cmp ah, 1
je even
mov ah, 9
lea dx, msg2
int 21h
jmp skip
even:
mov ah, 9
lea dx, msg1
int 21h
skip:
;prints a newline
mov ah, 2
mov dl, 0dh
int 21h
mov dl, 0ah
int 21h
loop looper
main endp
end main

No comments: