Forestellar
Forestellar

Reputation: 23

How to i convert string to integer when i get it from command line( ubuntu nasm 32bit)?

%include "asm_io.inc"

                 segment .data
                 segment .bss
argument         resb 32                    ; argument[32]


                 segment .text
                 global main
main:

                 enter 0,0

                 mov ebx, 4
                 mov ecx, dword [ebp + 4 * ebx]
                 mov eax, dword [ecx + 4]

                 mov [argument], eax

                 mov al, byte [argument + 0]
                 sub al, 48

                 call print_int          




end:             leave
                 mov eax, 0
                 ret

i am trying to convert string from command line to integer(for example, when i type $./Hello 30 at command line, '30' has to be the integer parameter for program(procedure)). After finding that [argument + 0] == '30', [argument + 1] = bin/bash, i thought i can get the right number with [argument + 0]. but the result is like -1075579555.

Even a little comment, it would be very helpful. thank you

Upvotes: 0

Views: 184

Answers (1)

Sep Roland
Sep Roland

Reputation: 39166

When your program starts the stack is laid out like this

       0
       Address of last environment string
       ...
       Address of 2nd environment string
       Address of 1st environment string
       0
       Address of last program argument
       ...
       Address of 2nd program argument
       Address of 1st program argument
       Address of program path
ESP -> Number of arguments

For your task you need to fetch the address to the 1st program argument.
You'll find it at dword [esp + 8].

Right after the execution of enter 0,0 and because that instruction pushed the EBP register, you'll find it at dword [esp + 12] == dword [ebp + 12].

enter   0,0                   ; Same as PUSH EBP : MOV EBP, ESP

mov     ebx, dword [ebp + 12] ; Address of first argument
movzx   eax, byte [ebx]       ; First character, is e.g. "3"
sub     al, "0"               ; Convert from "3" -> 3
imul    eax, 10               ; EAX now holds 3 * 10 == 30
mov     dl, byte [ebx + 1]    ; Second character, is e.g. "5"
sub     dl, "0"               ; Convert from "5" -> 5
add     al, dl                ; EAX now holds 3 * 10 + 5 == 35

call    print_int             ; Prints "35"

Upvotes: 2

Related Questions