Fibonacci Framework in C
#include <stdio.h>
#include <stdlib.h>
extern unsigned int fib(int);
unsigned int fib_c(int);
void printme(unsigned int, unsigned int);
int main(int argc, char* argv[])
{
unsigned int n = atoi(argv[1]);
unsigned int f1 = fib_c(n);
unsigned int f2 = fib(n);
printme(f1, f2);
return 0;
}
unsigned int fib_c(int n)
{
int a = 0;
int b = 1;
int k = 0;
for (int i = 0; i <=n; i++)
{
a = b;
b = k;
k = a + b;
}
return b;
}
void printme(unsigned int a, unsigned int b)
{
printf("c : %d\n", a);
printf("asm: %d\n", b);
(a==b) ? printf("true") : printf("false");
printf("\n");
}
Fibonacci in NASM
section .data
section .text
global fib
fib:
;STACK SAVE
push rbp
push rbx
mov rbp, rsp ;neuer Stackframe
;CODE
xor rax, 0 ;falls n=0 dann rax=0
cmp rdi, 0
je n_gleich_1_oder_0
mov r8,0 ;Laufvariablen also x1,x2
mov r9,1
dec rdi ;Indexverschiebung vor Rekursion
;um die richtigen Ergebnise zu bekommen
loop:
mov rsi, r9 ;Laufvariable k ist Register rsi
add rsi, r8 ;Rekursionsschritt
mov rax, rsi
mov r8, r9 ;neues x1 = altes x2
mov r9, rsi ;neues x2 = altes k
cmp rdi, 0 ;falls n=1 dann rax=1
je n_gleich_1_oder_0
dec rdi ;Index n dekrementieren
jnz loop ;um Anker zu erreichen
n_gleich_1_oder_0:
;STACK RESTORE
pop rbx
pop rbp
ret