1

I am trying to fill an array with values of the Fibonacci sequence. The line that I am having trouble with is one in which I am trying to determine whether or not the requested Fibonacci number is even. Something like modulus would possibly make sense.. I have been searching the web and am unable to find the solution. Also if any one could provide pointers on other places I may be going wrong in the code, it would be much appreciated as I have tried but I have no doubt there are other mistakes.

.386
.model flat, stdcall 
.stack 4096
INCLUDE Irvine32.inc
ExitProcess PROTO, dwExitCode: DWORD

.data
array DWORD size DUP 3 (99h)

.code
main PROC 
mov eax, 0          
mov ecx, 1           

L1: 
sub ebx, 2
cmp ebx, 0 
jz Finish
add eax + ecx
add ecx + eax
LOOP L1


FINISH
;If eax and 1 is false jump to finish even need help here
mov edx, eax
ret    

FINISHEVEN
mov edx, ecx
ret

call DumpMem

INVOKE ExitProcess, 0 
main ENDP
END main 
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • 1
    You can isolate the lowest bit since that signals if a number is even or odd in binary. E.g. use `and foo, 1`. – Jester Oct 27 '19 at 22:51
  • 1
    And if you don't want to destroy the value you're checking, you can use `test` instead of `and`. – Nate Eldredge Oct 28 '19 at 02:03
  • Unrelated to your specific question: Your loop looks super broken; the (slow) `loop` instruction is like `dec ecx`/`jnz` so it's going to modify the registers you're using to accumulate Fib(n). Also, `add eax + ecx` isn't value MASM syntax; I assume you mean `add eax, ecx`. – Peter Cordes Oct 28 '19 at 02:34
  • I got good results with google for `site:stackoverflow.com x86 even number`. – Peter Cordes Oct 28 '19 at 02:37

1 Answers1

2

The hint is already in your comment: you want to see whether eax AND 1 is zero or not.

You could do

and eax, 1
jz FINISHEVEN

However, then the value in eax will be the result of the logical AND, and based on your code you want to have the return value in edx. So you would want to mov edx, eax before this code.

Another way is to use the test instruction, which is like and except that it discards the result of the logical AND, leaving the original registers unchanged and only setting the flags. Then you could do

test eax, 1
jz FINISHEVEN
mov edx, eax
ret
Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82