Skip to content

Instantly share code, notes, and snippets.

@enh
Created December 13, 2023 04:13
Show Gist options
  • Save enh/79df9d919e7c69c1762b3c5e11e84bac to your computer and use it in GitHub Desktop.
Save enh/79df9d919e7c69c1762b3c5e11e84bac to your computer and use it in GitHub Desktop.
2023 adventofcode.com (arm64 assembler)
// https://adventofcode.com/2023/day/1
// as -o one.o one.s && ld -o one one.o
// echo -e "1abc2\npqr3stu8vwx\na1b2c3d4e5f\ntreb7uchet\n" | ./one
.equ __NR_read, 63
.equ __NR_write, 64
.equ __NR_exit_group, 94
.text
.global _start
_start:
mov x6, #0 // total
next_line: bl get_line
cbz x0, done
bl scan_line
// n = 10*first + last
mov x10, #10
madd x4, x10, x4, x5
// total += n
add x6, x6, x4
b next_line
done: mov x0, x6
bl print_int
mov x8, #__NR_exit_group
svc 0
.global scan_line
scan_line:
adrp x0, buf
add x0, x0, :lo12:buf
mov x1, #0
mov x4, #-1 // first digit
mov x5, #-1 // last digit
scan_next: ldrb w2, [x0, x1]
cbz x2, scan_done
add x1, x1, #1
// digit?
sub x3, x2, #'0'
cmp x3, 9
bhi scan_next
// do we have a first digit yet?
cmp x4, #0
csel x4, x3, x4, lt
// whatever we just saw is by definition last [so far]
mov x5, x3
b scan_next
# TODO: what if there were no digits?
scan_done: ret
.global get_line
get_line:
adrp x1, buf
add x1, x1, :lo12:buf
mov x3, #0
get_char: mov x0, #0
mov x2, #1
mov x8, #__NR_read
svc 0
cmp x0, #0
ble read_failed
ldrb w2, [x1]
add x1, x1, #1
add x3, x3, #1
cmp x3, #80
bge read_failed
cmp x2, #'\n'
bne get_char
cmp x3, #1
ble read_failed
sub x1, x1, #1
strb wzr, [x1]
mov x0, #1
ret
read_failed: mov x0, #0
ret
.global print_int
print_int:
adrp x1, buf
add x1, x1, :lo12:buf
add x1, x1, #32
mov x3, x1
mov x10, #10
mov x2, #'\n'
sub x1, x1, #1
strb w2, [x1]
print_loop: cbz x0, print_done
// x9 = x0/10, x2 = x0%10
mov x8, #10
sdiv x9, x0, x8
msub x2, x9, x8, x0
add x2, x2, #'0'
mov x0, x9
sub x1, x1, #1
strb w2, [x1]
b print_loop
print_done: mov x0, #1
sub x2, x3, x1
mov x8, #__NR_write
svc 0
ret
.bss
.global buf
buf:
.zero 80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment