我正在尝试将用户输入的数字字符串转换为整数。
例如,用户输入“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/