# X86 ASM question!

This topic is 3546 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am trying to learn some X86 assembly, and found this code on the internet. The code is supposed to allow the user to enter a number, then determine whether it is prime or not. My question is in section L3 of isPrime. As far as I can see, this code only jumps to this section if the number in EAX is 1 or 2, but it also appears to be the only section that sets the ZERO flag! How does it handle a prime number that isnt 1 or 2? Also in the isPrime function: how does the program escape the loop in section L1? It appears to be infinite to me. Sorry if these are stupid questions, I am only familiar with ARM assembly. EDIT: The Irvine32.inc is just a library that allows you to read and write to the console in Windows, if you see a call not included, its from Irvine32
INCLUDE Irvine32.inc

.data
heading BYTE "*** Prime Number Program *** (DEMO)",
0dh,0ah,0dh,0ah,0

prompt BYTE "Enter an integer between 2 and 2,147,483,647, ",
0dh,0ah,
"or enter 0 to quit: ",0
msgPrime BYTE " is prime.",0dh,0ah,0
msgNotPrime BYTE " is not prime.",0dh,0ah,0

.code
main PROC
call ClrScr
call WriteString

L1: call Crlf
mov  edx,OFFSET prompt
call WriteString
call Crlf
cmp  eax,0		; does user want to quit?
jle  Exit_main		; yes

call IsPrime		; is EAX prime?
.IF ZERO?		; yes:
mov  edx,OFFSET msgPrime	; display "is prime"
.ELSE		; no:
mov  edx,OFFSET msgNotPrime	; display "is not prime"
.ENDIF

call WriteDec		; display the number
call Writestring		; display the message
jmp  L1

Exit_main:
call Clrscr
exit
main ENDP

;---------------------------------------------------------
IsPrime PROC
;
; Checks the integer in EAX to see if it is prime. If so,
; returns with ZF = 1; otherwise, clears the Zero flag.
;---------------------------------------------------------
pusha
cmp eax,2		; 1 and 2 are special cases
jbe L3		; both are prime

mov ecx,eax	   	; get number for loop count
shr ecx,1		; divide by 2
mov ebx,2		; first divisor

L1:	call IsDivisible   		; EAX divisble by EBX?
jz L4		; yes: quit
inc ebx		; next divisor
loop L1

L3:	test eax,0		; prime, so set the Zero flag
jmp L5

L4:	or eax,0		; not prime, so clear the Zero flag
jmp L5

L5:	popa
ret
IsPrime ENDP

;------------------------------------------------------
IsDivisible PROC
;
; Sets the Zero flag if EAX is evenly divisible by EBX.
;------------------------------------------------------
push  eax
push  edx
mov   edx,0
div   ebx	; divide EAX by EBX
cmp   edx,0	; remainder = 0?
pop   edx
pop   eax
ret
IsDivisible ENDP

END main



##### Share on other sites
the loop instruction decrements ecx and will jump only if ecx is not 0, so eventually L1 will fall through to L3.

1. 1
2. 2
Rutin
18
3. 3
4. 4
5. 5
frob
13

• 11
• 9
• 30
• 16
• 9
• ### Forum Statistics

• Total Topics
632611
• Total Posts
3007417

×