Skip to content

Commit 62df166

Browse files
committed
print_int fix ascii
1 parent f1c11b4 commit 62df166

2 files changed

Lines changed: 28 additions & 15 deletions

File tree

print_int/Makefile

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,9 @@ build:
44

55
run: build
66
./print_int
7+
8+
check: build
9+
./print_int | md5sum | grep -q ^823c843e5 && printf "\033[1;32m[OK]\033[0m\n"
10+
11+
clean:
12+
rm -f print_int

print_int/print_int.s

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,14 @@
2222
.text
2323
.globl _start
2424

25-
# char *rsi, int rdx;
26-
print_chars:
27-
movq $WRITE, %rax
28-
movq $STDOUT, %rdi
25+
# char *rsi, int rdx
26+
write_string:
27+
mov $WRITE, %rax
28+
mov $STDOUT, %rdi
2929
syscall
3030
ret
3131

32-
# Prints hexadecimal value in rsi to stdout.
32+
# int rsi
3333
print_int:
3434
push %rax
3535
push %rbp
@@ -38,29 +38,36 @@ print_int:
3838
push %rcx
3939
mov %rsp, %rbp # save stack pointer
4040
mov $0, %rcx
41-
movb $0xa, -64(%rbp, %rcx)
41+
push $0xa # "\n"
4242
inc %rcx
43-
print_int_loop:
43+
print_int_push_loop:
4444
mov %rsi, %rax
4545
and $15, %rax
4646
add $48, %rax # %rax now contains ascii "0"-"9"
4747
cmp $57, %rax
4848
jle print_int_after_adjust
4949
add $39, %rax # adjust for ascii "a"-"f"
5050
print_int_after_adjust:
51-
movb %al, -64(%rbp, %rcx)
51+
push %rax
5252
inc %rcx
5353
shr $4, %rsi
5454
test %rsi, %rsi
55-
jnz print_int_loop
56-
movb $0x78, -64(%rbp, %rcx)
55+
jnz print_int_push_loop
56+
push $0x78 # "x"
5757
inc %rcx
58-
movb $0x30, -64(%rbp, %rcx)
58+
push $0x30 # "0"
5959
inc %rcx
60-
leaq -64(%rbp), %rsi
61-
mov %rcx, %rdx # len
62-
le_print:
63-
call print_chars
60+
mov $0, %rdx
61+
print_int_pop_loop: # copy chars from stack
62+
pop %rax
63+
movb %al, -128(%rbp, %rdx)
64+
inc %rdx
65+
cmp %rsp, %rbp
66+
jne print_int_pop_loop
67+
lea -128(%rbp), %rsi
68+
mov %rcx, %rdx
69+
call write_string
70+
6471
mov %rbp, %rsp # restore stack pointer
6572
pop %rcx
6673
pop %rdx

0 commit comments

Comments
 (0)