Skip to content

Instantly share code, notes, and snippets.

@ioquatix
Created December 5, 2019 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ioquatix/428e257fda3326a741cd262f25593079 to your computer and use it in GitHub Desktop.
Save ioquatix/428e257fda3326a741cd262f25593079 to your computer and use it in GitHub Desktop.
Fizz Buzz X86-64 (amd64) assembly (works on Linux)
.text
.global main
main:
# Save the non-volatile registers:
pushq %r15
pushq %r14
pushq %r13
pushq %r12
pushq %rbx
# Initialize the loop counter:
movl $1, %ebx
# Load the string literal addresses:
leaq FizzBuzz(%rip), %r14
leaq Fizz(%rip), %r15
leaq Buzz(%rip), %r12
leaq Format(%rip), %r13
Top:
# Compute i % 3 and i % 5:
movzbl %bl, %eax
imull $205, %eax, %ecx
shrl $10, %ecx
leal (%rcx,%rcx,4), %edx
imull $171, %eax, %eax
shrl $9, %eax
leal (%rax,%rax,2), %eax
negl %eax
movzbl %al, %ecx
addl %ebx, %ecx
movl %ebx, %eax
subl %edx, %eax
movl %ecx, %edx
# Decide what to print:
orb %al, %dl
je PutsFizzBuzz
testb %cl, %cl
je PutsFizz
testb %al, %al
je PutsBuzz
movq %r13, %rdi
movl %ebx, %esi
xorl %eax, %eax
callq printf
jmp Next
PutsFizzBuzz:
movq %r14, %rdi
jmp CallPuts
PutsFizz:
movq %r15, %rdi
jmp CallPuts
PutsBuzz:
movq %r12, %rdi
CallPuts:
callq puts
Next:
incl %ebx
cmpl $101, %ebx
jne Top
# Set the return valueto 0:
xorl %eax, %eax
# Restore the non-volatile registers:
popq %rbx
popq %r12
popq %r13
popq %r14
popq %r15
# Return:
retq
Format:
.asciz "%d\n"
Buzz:
.asciz "Buzz"
Fizz:
.asciz "Fizz"
FizzBuzz:
.asciz "FizzBuzz"
@ioquatix
Copy link
Author

ioquatix commented Dec 5, 2019

It was modified from compiling

#include <stdio.h>

int main() {
    for (int i = 1; i <= 100; i += 1) {
        if (i % 3 == 0 && i % 5 == 0) printf("FizzBuzz\n");
        else if (i % 3 == 0) printf("Fizz\n");
        else if (i % 5 == 0) printf("Buzz\n");
        else printf("%d\n", i);
    }
}

To produce the initial assembly:

clang -S -Os -Wall -fomit-frame-pointer -fno-asynchronous-unwind-tables fizzbuzz.c

To compile the above assembly (in a file called fizzbuzz.s):

clang -o fizzbuzz fizzbuzz.s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment