Skip to content

Instantly share code, notes, and snippets.

@kariya-mitsuru
Created May 8, 2020 01:45
Show Gist options
  • Save kariya-mitsuru/c222efe5c6cf67844ef7d1256c1df5e0 to your computer and use it in GitHub Desktop.
Save kariya-mitsuru/c222efe5c6cf67844ef7d1256c1df5e0 to your computer and use it in GitHub Desktop.
x64 Assembly FizzBuzz(236bytes version, Thanks @fujitanozomu for using stack instead of sbrk)
# vim: ts=8 sw=8
# build and execute
# $ gcc -mx32 -nostdlib -static -s -Wl,--build-id=none,-Ttext,0x400074 fizzbuzz.s
# $ dd if=a.out of=fizzbuzz count=236 bs=1
# $ chmod +x fizzbuzz
# $ ./fizzbuzz
.text
.Sfizzbuzz:
.ascii "Fizz"
.ascii "Buzz\n"
.ascii "Fizz\n"
.Lcheck:
add $4, %esi
xor %edx, %edx
mov %ebp, %eax
div %ebx
test %edx, %edx
mov $5, %dl # mov $5, %edx
ret
.global _start
_start:
# loop index
xor %ebp, %ebp
# divisor
xor %ebx, %ebx
.Lloop:
# increment loop index
inc %ebp
# check multiple of 15
mov $.Sfizzbuzz-4, %esi
mov $15, %bl # mov $15, %ebx
call .Lcheck
mov $9, %dl # mov $9, %edx
je .Loutput
# check multiple of 5
mov $5, %bl # mov $5, %ebx
call .Lcheck
je .Loutput
# check multiple of 3
inc %esi
mov $3, %bl # mov $3, %ebx
call .Lcheck
je .Loutput
# convert number to string
lea -1(%rsp), %esi
mov %ebp, %eax
mov $10, %bl # mov $10, %ebx
mov %bl, (%rsi)
.Ltostrloop:
xor %edx, %edx
div %ebx
add $'0', %dl
dec %esi
mov %dl, (%rsi)
test %eax, %eax
jne .Ltostrloop
# calculate # of bytes for output
mov %esp, %edx
sub %esi, %edx
.Loutput:
# write(1, %rsi, %rdx)
xor %eax, %eax
inc %eax # mov $1, %eax
mov %eax, %edi # mov $1, %edi
syscall
# check loop condition
cmp $40, %ebp
jl .Lloop
.Lexit:
# exit(0)
xor %edi, %edi
xor %eax, %eax
mov $60, %al # mov $60, %eax
syscall
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment