title: MASM: integer to string using std and stosb
body: <p>I have the following procedure for converting a user supplied integer to a string. 
  I'm pretty sure my algorithm is working fine for converting each digit of the integer to it's correct decimal ASCII value. However, I'm having difficulty then storing that digit into its correct place in the outString. </p>
  
  <p>I've set the direction flag using 'std', and I then use stosb to load the current, converted digit into the last byte in outString (read from back to front). However, this does not seem to work.</p>
  
  <p>If I get rid of 'std', I can store my converted integer in reverse. E.g 1993 gets stored in outString as '3991', but obviously that's in error. </p>
  
  <p>Would appreciate some assistance. Am I using 'std' wrong? 
  Thanks!</p>
  
  <pre><code>writeVal PROC
  
  ; SET up the stack frame 
  push    ebp     ;old value of ebp stored on the system stack
  mov ebp, esp    ;ebp now contains value of esp, which is address of top of stack
  
  
  mov edi, [ebp + 8]      ; EDI = @outString
  
  
  
  std                 ; set direction flag. allows us to add chars to the end of outString
  
  
  mov eax, [ebp + 12] ; EAX = userInt
  
  convertInt:             ; the int-&gt;string conversion is a post-test loop to handle case where user input '0' as a string
  
      mov ebx, 10d            ; EBX = divisor of 10
      cdq                 ; prep for division
      div ebx             ; EAX = quot, EDX = remainder
  
      add edx, 48         ; convert EDX to ASCII char value
  
      push    eax             ; store current value in EAX
      mov eax, edx            ; set EAX to the converted ASCII value
  
  
      stosb               ; store the converted char at the end of outString
  
      pop eax             ;restore value of EAX
  
      call WriteDec
      call CrLf
  
      cmp eax, 0
      je  finished            ; if eax = 0, it means we have fully converted userInt to a string
      jmp convertInt      ; else, repeat
  
  finished:
      displayString [ebp + 8] ; print the converted outString
  
      pop ebp
      ret 8
  writeVal ENDP 
  </code></pre>