Skip to content

Instantly share code, notes, and snippets.

@banderlog
Last active March 20, 2017 09:02
Show Gist options
  • Save banderlog/110e156b74f578becae815513b7007f5 to your computer and use it in GitHub Desktop.
Save banderlog/110e156b74f578becae815513b7007f5 to your computer and use it in GitHub Desktop.
;; fibonacci.asm ;;
;; print fibonacci numbers up to 1000000000 ;;
global _start
section .bss
array2 resb 512 ;for converted output
section .text
;;;;;;;;;;;;;;;;;;;;;; FIBONACCI GENERATOR ;;;;;;;;;;;;;;;;;;;;;;;;;;
input: ;numbers will be stored in [input]
%assign i 1 ;
%assign j 1 ;
%rep 1000000000 ;lim of fibonacci num - 1
%if j > 1000000000 ;
%exitrep ;
%endif ;
;
dd j ;
;
%assign k j+i ;
%assign i j ;
%assign j k ;
%endrep ;
inlen equ ($-input)/4 ;amount of 4 byte elements
;;;;;;;;;;;;;;;;;;;;;;; MAIN PART ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
_start:
xor ecx, ecx ;stack depth counter
mov edi, -1 ;crutch for cell in input counter
mov esi, -1 ;crutch for place in output counter
cycle: ;main cycle
mov [array2+esi],byte 10;put \r in output after each number
inc esi ;place in output counter ++
inc edi ;new 4 byte cell from input
cmp edi, inlen ;input ended?
jz exit ; if YES, go to exit
mov eax, [input+edi*4] ;if NO, prepare to divide eax by
mov ebx, 10 ; ebx (123 -> 1,2,3)
;;;;;;;;;;;;;;;;;;;;;;; PROCESS 1 CELL OF INPUT ;;;;;;;;;;;;;;;;;;;;;
chop: ;123 -> 1,2,3
xor edx, edx ;prepare EDX:EAX
div ebx ;divide eax by ebx
add edx, 00110000b ;convert remainder to ascii
test eax, eax ;is anything left to divide
jnz prpchop ;if YES -> prepare to do it again
transf: ;if NO -> transfer to output array
mov [array2+esi], dl ;move it to array, only 1 byte
inc esi ;place in output array ++
test ecx, ecx ;anything to add in stack?
jz cycle ;if NO -> go for next cell
pop edx ;if YES -> pull it out
dec ecx ;stack depth --
jmp transf ;transfer to output array
prpchop: ;prepare to chop again
push edx ;save prev remainder from division
inc ecx ;stack depth counter ++
xor edx, edx ;prepare EDX
jmp chop ; -> chop
exit: ;almost done ^_^
;;;;;;;;;;;;;;;;;;;;;;; OUTPUT LENGTH CALCULATION ;;;;;;;;;;;;;;;;;;;;
xor ecx, ecx ;prepare counter
lp: cmp byte [array2+ecx],0 ;end of output array?
jz end ;if YES -> stop count
inc ecx ;if NO -> keep count
jmp lp ;do it again
end: ;done ^_^
;;;;;;;;;;;;;;;;;;;;;;; PRINT AND EXIT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov eax, 4 ;write
mov ebx, 1 ; to standard output
mov ecx, array2 ; start of output array
mov edx, ecx ; length of output array
int 80h ; syscall (do it)
mov eax, 1 ;exit
mov ebx, 1 ; all ok
int 80h ; do it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment