Have you ever wondered how does look the computation of Fibonnaci number in assembly?
For sake of curiosity I chose Pep/8 Assembler and Simulator which could be found on
http://code.google.com
The original C uncached version looks as following:
#include <iostream>
using namespace std;
int fib (int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fib (n - 1) + fib (n - 2);
}
}
int main ()
{
int num;
cout << "Which Fibonacci number? ";
cin >> num;
cout << "The number is " << fib (num) << endl;
return 0;
}
The Pep/8 implementation:
BR main
;
;************** int fib (int n)
retValue:.EQUATE 4 ;returned value
n: .EQUATE 2 ;formal parameter
fib: LDA n,s ;if (n == 0)
BRNE elseIf
LDA 0x0000,i
STA retValue,s ;return 0;
RET0
elseIf: CPA 0x0001,i ;else if (n == 1)
BRNE else
LDA 0x0001,i
STA retValue,s ;return 1;
RET0
else: SUBA 1,i ;return fib (n - 1);
STA -4,s
SUBSP 4,i
CALL fib
ADDSP 4,i
LDA -2,s
STA retValue,s
LDA n,s
SUBA 2,i ;n-2
STA -4,s
SUBSP 4,i
CALL fib
ADDSP 4,i
LDA retValue,s
ADDA -2,s
STA retValue,s ;+ fib (n - 2)
RET0
;
;*****************************main()
num: .EQUATE 0 ;local variable
main: SUBSP 2,i ;allocate num
STRO msg1,d ;cout<<"Which Fibonacci Number? " DECI num,s ;cin >> num
LDA num,s
STA -4,s ;push n
SUBSP 4,i
CALL fib ;push retAddr
ADDSP 4,i ;pop values
STRO msg2,d ;cout<< "The number is: "
DECO -2,s ;<<fib(num)
CHARO '\n',i ;<< endl
ADDSP 2,i ;deallocate num
STOP
msg1: .ASCII "Which Fibonacci Number?\x00" msg2: .ASCII "The number is: \x00"
.END
The screenshot of the running pep/8 code:
Comments (0)
RSS Collapse / ExpandOnly registered and authorized users can leave comments. Login or Register