-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprintNumStack.asm
More file actions
71 lines (56 loc) · 1.83 KB
/
printNumStack.asm
File metadata and controls
71 lines (56 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
option casemap:none
extern GetProcessHeap:proc
extern HeapAlloc:proc
extern ExitProcess:proc
.data
allocSize dq 32 ; Size of the memory to allocate
num dq 123456 ; The number to convert to a string
.code
main proc
sub rsp, 40h ; Allocate stack space for local variables
call GetProcessHeap ; Get the process heap handle
mov rcx, rax ; Store the heap handle in rcx
mov rdx, 0 ; Zero out rdx for the flags parameter
mov r8, allocSize ; Size of the memory to allocate
call HeapAlloc ; Allocate memory from the heap
sub rsp, 40h ; Allocate space for the string (32 bytes)
mov rcx, num ; Load the number to convert into rcx
mov rdx, rax ; Pointer to the allocated memory for the string in rdx
call convert ; Convert the number to a string
add rsp, 40h ; Adjust stack pointer for alignment
; Clean up and exit
add rsp, 40h ; Deallocate stack space
xor ecx, ecx ; Set exit code to 0
call ExitProcess ; Exit the process
main endp
; Convert a number to a string representation
; rcx - the number to convert
; rdx - pointer to the allocated memory for the string
; returns the number of characters written in rax, including the trailing \0 (this might be wrong, check when outputing to console)
convert proc
mov r8, rdx ; store the memory pointer
mov r10, 10 ; divide by base 10
; start by writing the trailing \0
xor dl, dl
push rdx
mov rax, rcx ; rdx:rax are to be divided
Divide:
xor rdx, rdx
div r10
add dl, '0' ; char representation of the resulting remainder
push rdx
cmp rax, 0
jne Divide ; if there's more to divide, keep going
; otherwise write to memory
xor r9, r9
WriteResult:
pop rdx
mov [r8+r9], dl
inc r9
cmp dl, 0
jne WriteResult
mov rax, r9 ; return the number of writen characters
; this might need checking if we are still in the bounds of the allocated memory
ret
convert endp
end