Skip to content

Commit 6fd3884

Browse files
committed
some refactoring in print_int
1 parent d696d35 commit 6fd3884

2 files changed

Lines changed: 25 additions & 45 deletions

File tree

print_int/print_int

-104 Bytes
Binary file not shown.

print_int/print_int.s

Lines changed: 25 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,8 @@
1717
.equ BANG, 0x21
1818
.equ NEWLINE, 0xa
1919

20-
2120
.data
2221

23-
my_number:
24-
.quad 0x41
25-
2622
.text
2723
.globl _start
2824

@@ -33,58 +29,42 @@ print_chars:
3329
syscall
3430
ret
3531

36-
# void print_int_h(int {rsi});
37-
# Prints hexadecimal value in {rsi} to stdout.
38-
_print_int_h:
32+
# Prints hexadecimal value in rsi to stdout.
33+
print_int:
3934
push %rax
4035
push %rbp
4136
push %rsi
4237
push %rdx
43-
44-
mov %rsp, %rbp # save base stack pointer
45-
46-
# value is kept in {rsi} and low bits are shifted off, four by four
47-
# do all arithmetic in {rax}
48-
49-
# move trailing '\n' onto stack
50-
push $0xa
51-
52-
_loop:
53-
54-
mov %sil, %al #
55-
and $15, %al # %al contains low nibble of %rsi
56-
add $48, %al # %al now correctly contains ascii "0"-"9"
57-
cmp $57, %al #
58-
jle _insert_byte
59-
add $39, %al # adjust %al for ascii "a"-"f"
60-
_insert_byte:
61-
dec %rsp
62-
mov %al, (%rsp) # move this ascii value into next slot on stack
63-
shr $4, %rsi # go on to next lowest bit
64-
test %rsi, %rsi # loop until nothing nonzero left
65-
jnz _loop
66-
67-
# move leading '0x' onto stack
68-
push $0x78 #x
69-
push $0x30 #0
70-
71-
# get ready to print
72-
mov %rbp, %rdx ##
73-
sub %rsp, %rdx ## %rdx will be length of number in bytes
74-
mov %rsp, %rsi ## address of top of stack
75-
call print_chars ## print out bytes
76-
mov %rbp, %rsp ## restore stack pointer
77-
38+
mov %rsp, %rbp # save stack pointer
39+
push $0xa # "\n"
40+
print_int_loop:
41+
mov %rsi, %rax
42+
and $15, %rax
43+
add $48, %rax # %rax now contains ascii "0"-"9"
44+
cmp $57, %rax
45+
jle print_int_after_adjust
46+
add $39, %rax # adjust for ascii "a"-"f"
47+
print_int_after_adjust:
48+
push %rax
49+
shr $4, %rsi
50+
test %rsi, %rsi
51+
jnz print_int_loop
52+
push $0x78 # "x"
53+
push $0x30 # "0"
54+
mov %rsp, %rsi
55+
mov %rbp, %rdx
56+
sub %rsp, %rdx # print from rsp to rbp
57+
call print_chars
58+
mov %rbp, %rsp # restore stack pointer
7859
pop %rdx
7960
pop %rsi
8061
pop %rbp
8162
pop %rax
82-
8363
ret
8464

8565
_start:
86-
mov my_number, %rsi
87-
call _print_int_h
66+
mov $0xdeadbeef, %rsi
67+
call print_int
8868
jmp _exit
8969

9070
_exit:

0 commit comments

Comments
 (0)