sh-5.2$ cat main.s
.section .text
# long long atoq(const char *ptr);
atoq:
xorq %rax, %rax
xorq %rcx, %rcx
1: movb (%rdi), %cl
cmpb $'0', %cl
jb 1f
cmpb $'9', %cl
ja 1f
subq $'0', %rcx
movq $10, %rdx
mulq %rdx
addq %rcx, %rax
incq %rdi
jmp 1b
1: movq %rdi, %rdx
retq
# long long qtoa(char *ptr, long long value);
qtoa:
movq %rsi, %rax
movq %rdi, %rsi
movq $10, %rcx
1: xorq %rdx, %rdx
divq %rcx
addq $'0', %rdx
movb %dl, (%rdi)
incq %rdi
cmpq $0, %rax
jne 1b
movq %rdi, %rax
subq %rsi, %rax
decq %rdi
1: movb (%rdi), %dh
movb (%rsi), %dl
movb %dh, (%rsi)
movb %dl, (%rdi)
incq %rsi
decq %rdi
cmpq %rsi, %rdi
ja 1b
retq
.global _start
_start:
subq $1024, %rsp
movq $0, %rax # sys_read
movq $0, %rdi # stdin
movq %rsp, %rsi # buf
movq $1023, %rdx # count
syscall
# buf[--count] = '\0';
decq %rax
movb $0, (%rsp, %rax)
movq %rsp, %rdi
callq atoq
movq %rax, %r12
movq %rdx, %rdi
incq %rdi
callq atoq
movq %rax, %r13
movq %r12, %rax
mulq %r13
movq $2, %rcx
divq %rcx
movq %rsp, %rdi
movq %rax, %rsi
callq qtoa
movb $'\n', (%rsp, %rax)
incq %rax
movq %rax, %rcx
movq $1, %rax # sys_write
movq $1, %rdi # stdout
movq %rsp, %rsi # buf
movq %rcx, %rdx # count
syscall
1: movq $60, %rax # sys_exit
xorq %rdi, %rdi # error_code
syscall
jmp 1b
sh-5.2$ as -g -o main.o main.s
sh-5.2$ ld -o main main.o
sh-5.2$ ./main
10 20
100
sh-5.2$ ./main
19 8
76
sh-5.2$ ./main
19 7
66
sh-5.2$