danieljon.es

index posts opinions portfolio

Posts

My posts about programming and things.
Date format is day/month/year because I'm sane.

x86 Assembly

16/7/2018

A little while ago I temporarily became interested in 8085 assembly and wrote a few little exercises and quickly lost interest. However, the basics were retained and I was highly interested in some day coming back to it.

Over the last few days I have been looking at x86 assembly (Intel syntax, NASM assembler) and have followed various tutorials and videos furthering my existing, yet basic knowledge. At this point I felt I was comfortable enough to attempt a small and simple exercise, I chose to generate Fibonacci numbers.

First, I wrote the program in C to understand the required logic flow.

#include <stdio.h>

int main(void)
{
	int i, tmp;
	int first = 0;
	int second = 1;
	printf("%d\n%d\n", first, second);
	for (i = 0; i < 10; i++)
	{	
		tmp = second;
		second += first;
		first = tmp;
		printf("%d\n", second);
	}
	return 0;
}
Using the C version, I translated the program into x86 assembly:

fibonacci.asm
%include 'functions.asm'

SECTION .data
MAX db 8	; 10 - 2 (we print those outside the loop) 

SECTION .text
global _start

_start:
	; eax -> first
	; ebx -> second
	; ecx -> counter
	; edx -> tmp
	; MAX -> maximum iterations
	mov eax, 0
	mov ebx, 1
	mov ecx, 0
	mov edx, 0

	; print the first iteration of values (0, 1)
	call printintlf
	push eax	; store eax on the stack
	mov eax, ebx 	; printintlf requires the int in eax
	call printintlf
	pop eax		; restore eax
loop:
	inc ecx	
	mov edx, ebx 	; store second as tmp data	
	add ebx, eax 	; add first to second
	mov eax, edx	; set first as what second was (tmp variable)
	push eax	; store eax on the stack
	mov eax, ebx	; printintlf requires the int in eax
	call printintlf
	pop eax		; restore eax
	cmp ecx, [MAX] 	; check if our counter has reached MAX, if it hasn't loop
	jne loop

	call exit
'functions.asm' is a file containing some standard functions for string/int printing, exiting etc. I wrote the functions following the tutorials at asmtutor.com. You can find the file here if you care to see it.

I hope to spend considerably longer learning and writing programs this time.


RSS feed
FSF member

page generated 10/4/2023 using websitegenerator in C