Skip to content

Instantly share code, notes, and snippets.

@olavfosse
Created January 2, 2025 13:54
Show Gist options
  • Save olavfosse/189edf5e156a2e51720879569fff68c6 to your computer and use it in GitHub Desktop.
Save olavfosse/189edf5e156a2e51720879569fff68c6 to your computer and use it in GitHub Desktop.
fizzbuzz in x64 assembly written in ed (CODE GORE)
.intel_syntax noprefix
.global _start
# - [x] exit with 1337
#- [ ] print 1-100
.section .data
int_fmt: .string "%d\n"
.section .text
_start:
mov rcx, 100
iteration:
# start = 4, end = 4 (end is not excluseive)
mov r14, 4 # start
mov r15, 4 # end
# if divisble by 3, start = 0
mov rdi, 101
sub rdi, rcx
mov r13, 3
call divisible_by
jne not_divisible_by_3
mov r14, 0
not_divisible_by_3:
# if divisble by 5, end = 7
mov r13, 5
call divisible_by
jne not_divisible_by_5
mov r15, 8
not_divisible_by_5:
# if start == end, print_int, otherwise print [start..end]
cmp r14, r15
jne divisible_by_3_or_5
call print_int
mov rdi, rcx
jmp not_divisible_by_3_or_5
divisible_by_3_or_5:
call print_from_start_to_end
call print_newline
not_divisible_by_3_or_5:
loop iteration
mov rax, 60
mov rdi, 3
syscall
print_int:
mov r10, 10
mov rax, rdi
mov rdx, 0
div r10
add rdx, 48
mov byte [buffer+2], dl
# least significant digit written ^^^
mov rdx, 0
div r10
add rdx, 48
mov byte [buffer+1], dl
# second least significant digit wirtten ^^^
mov rdx, 0
div r10
add rdx, 48
mov byte [buffer], dl
call print_int_buf
call print_newline
ret
print_int_buf:
mov rax, 1
# rdi: the digit count
mov r11, rdi # count of how many more digits i need to print
# the buf contains the digits in reverse
lea rsi, [rip+buffer+1]
mov rbx, rcx
mov rdi, 1
mov rdx, 3
syscall
mov rcx, rbx
ret
print_digit:
add rdi, 48
mov [buffer+2], rdi
call print_int_buf
ret
print_newline:
mov rax, 1
mov rdi, 1
lea rsi, [rip+buffer+3]
mov BYTE PTR [rsi], 10
mov rbx, rcx
mov rdx, 1
syscall
mov rcx, rbx
ret
divisible_by:
# is rdi divisible by r13
xor rdx, rdx
mov rax, rdi
div r13
cmp rdx, 0
ret
print_from_start_to_end:
# prints from r14 to r15, will change r14 and r15
mov rax, 1
mov rdi, 1
lea rsi, [rip+strings]
add rsi, r14
mov rdx, r15
sub rdx, r14
mov rbx, rcx
syscall
mov rcx, rbx
ret
.section .bss
buffer:
.skip 4
.section .data
strings:
.ascii "fizz"
.ascii "buzz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment