string - 在 Assembly x86 中将数字字符串转换为整数

标签 string assembly x86 type-conversion int

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

例如,用户输入“1234”作为字符串,我希望将 1234 存储在 DWORD 变量中。
我使用 lodsb 和 stosb 来获取各个字节。我的问题是我无法找到适合它的算法。我的代码如下:

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 还很陌生,无法获得正确的语法。如果有人可以帮助解决该算法,那就太好了。谢谢!

最佳答案

一个简单的实现可能是

    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 值

关于string - 在 Assembly x86 中将数字字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42890917/

相关文章:

string - 在 Groovy 中,String.split(regex, int) 不会产生预期的结果

c - 这些功能有什么区别?

assembly - CS :APP example uses idivq with two operands?

assembly - 自动 x86 指令混淆

assembly - 为什么不将功能参数存储在XMM向量寄存器中?

c++ - 在 MSVC++ 中检查字节代码时遇到问题

string - 通过强制转换和使用串联运算符将整数附加到字符串

java - 在保留文字的同时修剪空格

assembly - 将 xmm 寄存器折叠为标量

c - 进程间信号量有时无法按预期工作