Guest User

itoa function in asm

a guest
Jun 29th, 2022
693
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. section .text
  2.   global _start
  3.  
  4. %include "includes/print.asm"      ; syscall to print to screen function
  5. %include "includes/leave.asm"      ; syscall to exit program
  6.  
  7. _start:
  8.  
  9.   mov ebx, 0                       ; i = 0 in loop
  10.  
  11. itoa_start:
  12.  
  13.   xor edx, edx                     ; clear edx
  14.   mov eax, [num]                   ; move value of num into eax
  15.   mov ecx, 10                      ; move 10 into ecx (divisor)
  16.   div ecx                          ; div ecx (ex. 1234 / 10 = 1234.5)
  17.   cmp edx, 0                       ; compare remainder (edx ex. .5) to 0
  18.   je itoa_end                      ; if remainder == 0 jump to end label
  19.   mov [num], eax                   ; move quotient (eax ex. 1234) into num (12345 -> 1234)
  20.   add edx, '0'                     ; add '0' (48) to remainder to convert into ASCII (5 -> '5')
  21.   mov [res + ebx], edx             ; move remainder into res value + ebx (ex. res + 0 -> '5')
  22.   add ebx, 1                       ; increase ebx value by 1
  23.  
  24.   jmp itoa_start
  25. itoa_end:
  26.   add ebx, 1                       ; increase ebx value by 1 for terminating string
  27.   mov word [res + ebx], 0          ; move 0 (terminator) into res + ebx
  28.  
  29.   mov ecx, res
  30.   mov edx, 5
  31.   call print                       ; print res string
  32.  
  33.   call leave
  34.  
  35. section .data
  36.   ; msg db "Enter num: "           ; Uncommenting this and running works as expected
  37.   ; msg_len equ $ - msg            ; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  38.  
  39.   ; msg db "HELLO"                 ; Uncommenting this and running gives another value (2863)
  40.   ; msg_len equ $ - msg            ; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  41.                                    ; Strangely, adding ": " to the end of "HELLO" makes it work fine
  42.  
  43.   num dw 12345                     ; Defining word num with value 12345
  44.  
  45. section .bss
  46.  
  47.   res resw 6                       ; Reserving word of 6 for res variable
  48.  
Advertisement
Add Comment
Please, Sign In to add comment