在Assembly x86中将一串数字转换为整数

时间:2017-03-19 19:05:38

标签: string assembly x86 type-conversion int

我试图将用户输入的数字字符串转换为整数。

例如,用户输入" 1234"作为一个字符串,我希望1234存储在一个DWORD变量中 我使用lodsbstosb来获取单个字节。我的问题是我无法获得适合它的算法。我的代码如下:

mov ecx, (SIZEOF num)-1
mov esi, OFFSET num
mov edi, OFFSET ints
cld

counter:
   lodsb
   sub al,48
   stosb
   loop counter

我知道ECX计数器也会有点关闭,因为它读取整个字符串而不仅仅是4个字节,因此它实际上是9因为字符串是10字节。

我试图使用10的幂来乘以单个字节,但我对Assembly来说很新,并且无法获得正确的语法。如果有人可以帮助解决那些很棒的算法。谢谢!

1 个答案:

答案 0 :(得分:1)

一个简单的实现可能是

    mov ecx, digitCount
    mov esi, numStrAddress

    cld                     ; We want to move upward in mem
    xor edx, edx            ; edx = 0 (We want to have our result here)
    xor eax, eax            ; eax = 0 (We need that later)

counter:
    imul edx, 10            ; Multiply prev digits by 10 
    lodsb                   ; Load next char to al
    sub al,48               ; Convert to number
    add edx, eax            ; Add new number
    ; Here we used that the upper bytes of eax are zeroed
    loop counter            ; Move to next digit

    ; edx now contains the result
    mov [resultIntAddress], edx

当然,有一些方法可以改进它,例如避免使用imul

编辑:修正了ecx值