Question

I'm programming an implementation of the Fibonacci sequence in assembly language, and I'm getting a strange bug. It works at first, but when I reach 8+13 (that is, 8+D in hex) it gives me 15. I'm compiling/running this with the Visual Studio 10 / MASM 32

Here's my code (Irvine32 is a library with some utility functions in it), and then I'll explain the output I get when I run it:

TITLE Fibonacci 

INCLUDE Irvine32.inc

.data

.code


main PROC

mov eax, 0
mov ebx, 1
mov ecx,12         ; set the loop counter to 12


    ;the 12 registry dumps display fib(1)-fib(12) in the eax register.
    ;As this is iteration based instead of loop based, the math comments
    ;in the loop are slighty off at the begining because of the edge condition
    ;so my comments about fib(n-1), etc. are valid only at fib(n) where n >= 2



 fib:   

    mov edx,eax  ;store fib(n-1) in a register temporarily
                 ;although the first time the loop runs,

    add eax,ebx  ;add fib(n-1) to fib(n-2) to get fib(n)
    mov ebx,edx  ;replace fib(n-2) with (fib n-1)

        ;at this point, eax holds fib(n), and ebx hold fib(n-1), which will be
        ;used to calculate fib (n+1) for the next loop iteration

    call DumpRegs

    loop fib

exit; exit the program
main ENDP

END main ; first procedure called is main

My eax register dumps from DumpRegs are, in order, 1, 1, 2, 3, 5, 8, D, 15, 22, 37, 59, 90

As you can see, this diverts from the correct Fib sequence where it is "D". So, how can I fix this, and more importantly, I want to understand what's happening here to cause this. Thanks!

edit: Alright, I see my silly mistake. Obviously all the output's in hex. Well, I guess this is just another reminder for me not to be hasty. Thanks again for your help!

Was it helpful?

Solution

UPDATE REMARK: Your code works, you're confused only because most of the output doesn't result in hex letters and looks like decimals. 15H is 21D, which is the correct number.

This should work:

    mov ax,0
    mov bx,1
    mov cx,12

  step:

    add ax, bx
    call DumpAX
    push ax ; or you can use DX to swap values of ax and bx - or xor op if you wish
    push bx
    pop ax
    pop bx
    loop step

    exit

OTHER TIPS

All your output is in hex. 0xD is 13, 0x15 is 21, 0x22 is 34 and so on. So the computation seems right, but your DumpRegs procedure is doing something weird.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top