Last active
May 6, 2020 00:10
-
-
Save ShinyaKato/85dfbe3453070d6057e8ba963de04496 to your computer and use it in GitHub Desktop.
x86-64 Assembly FizzBuzz on Linux
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
// build and execute | |
// $ gcc -o fizzbuzz fizzbuzz.s | |
// $ ./fizzbuzz | |
.section .rodata | |
.Sfizzbuzz: | |
.string "FizzBuzz\n" | |
.Sfizz: | |
.string "Fizz\n" | |
.Sbuzz: | |
.string "Buzz\n" | |
.Sformat: | |
.string "%d\n" | |
.text | |
.global main | |
main: | |
// function prologue | |
push %rbp | |
mov %rsp, %rbp | |
sub $16, %rsp | |
// -8(%rbp): loop index | |
mov $1, %rcx | |
mov %rcx, -8(%rbp) | |
.Lloop: | |
// check loop condition | |
mov -8(%rbp), %rcx | |
cmp $40, %rcx | |
jg .Lend | |
// check multiple of 15 | |
mov $0, %rdx | |
mov -8(%rbp), %rax | |
mov $15, %rdi | |
div %rdi | |
cmp $0, %rdx | |
jne .Lelse0 | |
// call printf | |
lea .Sfizzbuzz(%rip), %rdi | |
mov $0, %rax | |
call printf@PLT | |
jmp .Lendif | |
.Lelse0: | |
// check multiple of 3 | |
mov $0, %rdx | |
mov -8(%rbp), %rax | |
mov $3, %rdi | |
div %rdi | |
cmp $0, %rdx | |
jne .Lelse1 | |
// call printf | |
lea .Sfizz(%rip), %rdi | |
mov $0, %rax | |
call printf@PLT | |
jmp .Lendif | |
.Lelse1: | |
// check multiple of 5 | |
mov $0, %rdx | |
mov -8(%rbp), %rax | |
mov $5, %rdi | |
div %rdi | |
cmp $0, %rdx | |
jne .Lelse2 | |
// call printf | |
lea .Sbuzz(%rip), %rdi | |
mov $0, %rax | |
call printf@PLT | |
jmp .Lendif | |
.Lelse2: | |
// call printf | |
lea .Sformat(%rip), %rdi | |
mov -8(%rbp), %rsi | |
mov $0, %rax | |
call printf@PLT | |
.Lendif: | |
// increment loop index | |
mov -8(%rbp), %rcx | |
add $1, %rcx | |
mov %rcx, -8(%rbp) | |
jmp .Lloop | |
.Lend: | |
// set return value | |
mov $0, %rax | |
// function epilogue | |
mov %rbp, %rsp | |
pop %rbp | |
ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment