Last active
June 9, 2019 02:26
-
-
Save pedrominicz/ffe52a109764401b2cfd8b8bac41f6d6 to your computer and use it in GitHub Desktop.
Fizz Buzz in assembly.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
global _start | |
SECTION .data | |
fizz db 'fizz', 0 | |
buzz db 'buzz', 0 | |
newline db 10, 0 | |
SECTION .bss | |
buffer resb 256 | |
SECTION .text | |
; slen - string length | |
; in: | |
; eax: pointer to string | |
; out: | |
; eax: length of the string | |
slen: | |
push ecx | |
mov ecx, eax | |
.loop: | |
cmp byte [eax], 0 | |
jz .end | |
inc eax | |
jmp .loop | |
.end: | |
sub eax, ecx | |
pop ecx | |
ret | |
; sprint - print string to STDOUT | |
; in: | |
; eax: pointer to string | |
; out: | |
; eax: the number of bytes printed | |
sprint: | |
push ebx | |
push ecx | |
push edx | |
mov ecx, eax ; pointer to the string | |
; count the number of bytes in the string | |
push eax | |
call slen | |
mov edx, eax ; number of bytes | |
mov ebx, 1 ; write to STDOUT | |
mov eax, 4 | |
int 0x80 | |
; restore registers | |
pop eax | |
pop edx | |
pop ecx | |
pop ebx | |
ret | |
; iprint - print integer to STDOUT | |
; in: | |
; eax: integer | |
iprint: | |
push eax | |
push ebx | |
push ecx | |
push edx | |
mov ecx, 0 | |
mov ebx, 10 | |
.loop: | |
inc ecx | |
mov edx, 0 | |
div ebx | |
add edx, '0' | |
push edx | |
cmp eax, 0 | |
jne .loop | |
.print: | |
dec ecx | |
mov eax, esp | |
call sprint | |
pop edx | |
cmp ecx, 0 | |
jne .print | |
.end: | |
; restore registers | |
pop edx | |
pop ecx | |
pop ebx | |
pop eax | |
ret | |
_start: | |
mov ebx, 0 | |
.loop: | |
inc ebx | |
mov edi, 0 | |
.fizz: | |
mov eax, ebx | |
mov ecx, 3 | |
mov edx, 0 | |
div ecx | |
cmp edx, 0 | |
jne .buzz | |
inc edi | |
mov eax, fizz | |
call sprint | |
.buzz: | |
mov eax, ebx | |
mov ecx, 5 | |
mov edx, 0 | |
div ecx | |
cmp edx, 0 | |
jne .number | |
inc edi | |
mov eax, buzz | |
call sprint | |
.number: | |
cmp edi, 0 | |
jne .continue | |
mov eax, ebx | |
call iprint | |
.continue: | |
mov eax, newline | |
call sprint | |
cmp ebx, 100 | |
jne .loop | |
; invoke SYS_EXIT | |
mov ebx, 0 | |
mov eax, 1 | |
int 0x80 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment