I'm trying to take a string of numbers and convert it to an actual number. I can successfully convert it if it's just one digit, but I'm unsure how to convert a number with two or more digits.

section .data

str:    db      '3'     ;string to be converted

section .text
global  _start

_start:
mov     ebx, [str]
sub     ebx, 48         ;convert character to number

mov     eax, 1
int     0X80            ;exit, returning the converted number

Dani AI

Generated

The immediate problem is that mov ebx, [str] reads memory, not the address or a single ASCII byte. For multi-digit conversion you want a pointer register (ESI/EDI) that you increment and read one byte at a time, convert it from ASCII by subtracting '0', and build the result with the classic "result = result*10 + digit" step that described.

A compact, correct flow (NASM / Linux 32-bit) looks like this:

section .data
str:    db '12345', 0

section .text
global _start

_start:
    mov     esi, str        ; pointer to first character
    xor     eax, eax        ; result = 0

.parse:
    movzx   ecx, byte [esi] ; load byte and zero-extend
    cmp     cl, 0
    je      .done
    sub     cl, '0'
    cmp     cl, 9
    ja      .done           ; stop on non-digit
    imul    eax, eax, 10    ; result *= 10
    add     eax, ecx        ; result += digit
    inc     esi
    jmp     .parse

.done:
    ; result is in EAX. Returning via exit (int 0x80) only preserves 0..255.
    mov     ebx, eax
    mov     eax, 1
    int     0x80

Notes and gotchas:

  • Use movzx or mov al, [esi] to fetch a single byte. mov reg, [str+1] without a size will typically load a word/dword.
  • mov esi, str loads the address; mov esi, [str] loads the contents at that address.
  • Check for a leading '-' if negatives are needed, and watch for 32-bit overflow when parsing long strings.
  • For testing, write the number to stdout or use a debugger; using exit to return a large integer will truncate it to a byte.

Recommended Answers

All 3 Replies

123

First loop is 1
Second loop is 1*10+2
Third loop is 12*10+3

Ok, now I have another problem. I can easily access the second number in the string using mov eax, [str+1] However, this number can't be looped, so I try to do the same thing only using a register, which doesn't work. Does anyone know how to do this?
Thanks!

You put the address of the string in a register, then increment the register.

Read about indexing in your processor manual.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.