NASM Assembly convert input to integer?

后端 未结 2 2100
灰色年华
灰色年华 2020-11-22 04:16

Ok, so I\'m fairly new to assembly, infact, I\'m very new to assembly. I wrote a piece of code which is simply meant to take numerical input from the user, multiply it by 1

2条回答
  •  轮回少年
    2020-11-22 05:07

    Here's a couple of functions for converting strings to integers, and vice versa:

    ; Input:
    ; ESI = pointer to the string to convert
    ; ECX = number of digits in the string (must be > 0)
    ; Output:
    ; EAX = integer value
    string_to_int:
      xor ebx,ebx    ; clear ebx
    .next_digit:
      movzx eax,byte[esi]
      inc esi
      sub al,'0'    ; convert from ASCII to number
      imul ebx,10
      add ebx,eax   ; ebx = ebx*10 + eax
      loop .next_digit  ; while (--ecx)
      mov eax,ebx
      ret
    
    
    ; Input:
    ; EAX = integer value to convert
    ; ESI = pointer to buffer to store the string in (must have room for at least 10 bytes)
    ; Output:
    ; EAX = pointer to the first character of the generated string
    int_to_string:
      add esi,9
      mov byte [esi],STRING_TERMINATOR
    
      mov ebx,10         
    .next_digit:
      xor edx,edx         ; Clear edx prior to dividing edx:eax by ebx
      div ebx             ; eax /= 10
      add dl,'0'          ; Convert the remainder to ASCII 
      dec esi             ; store characters in reverse order
      mov [esi],dl
      test eax,eax            
      jnz .next_digit     ; Repeat until eax==0
      mov eax,esi
      ret
    

    And this is how you'd use them:

    STRING_TERMINATOR equ 0
    
    lea esi,[thestring]
    mov ecx,4
    call string_to_int
    ; EAX now contains 1234
    
    ; Convert it back to a string
    lea esi,[buffer]
    call int_to_string
    ; You now have a string pointer in EAX, which
    ; you can use with the sys_write system call
    
    thestring: db "1234",0
    buffer: resb 10
    

    Note that I don't do much error checking in these routines (like checking if there are characters outside of the range '0' - '9'). Nor do the routines handle signed numbers. So if you need those things you'll have to add them yourself.

提交回复
热议问题