因此,我正在尝试将字符串转换为数字,以便稍后向其中添加另一个数字。这是我必须在我的 .text 中进行转换的内容。 num2Entered 是用户输入的内容。 Num1plusNum2 是我最终要添加的标签。它们都在 .bss 部分中声明。任何帮助,将不胜感激!
mov ax, [num2Entered + 0]
sub ax, '0'
mov bx, WORD 1000
mul bx
mov [Num1plusNum2], ax
mov ax, [num2Entered + 1]
sub ax, '0'
mov bx, WORD 100
mul bx
add [Num1plusNum2], ax
mov ax, [num2Entered + 2]
sub ax, '0'
mov bx, WORD 10
mul bx
add [Num1plusNum2], ax
mov ax, [num2Entered + 3]
sub ax, '0'
add [Num1plusNum2], ax
最佳答案
每个字符只有一个字节,但您可能希望将其添加到更大的结果中。也可以选择 32 位......(如果你真的想要,可以将你的例程限制为 16 位)
mov edx, num3entered ; our string
atoi:
xor eax, eax ; zero a "result so far"
.top:
movzx ecx, byte [edx] ; get a character
inc edx ; ready for next one
cmp ecx, '0' ; valid?
jb .done
cmp ecx, '9'
ja .done
sub ecx, '0' ; "convert" character to number
imul eax, 10 ; multiply "result so far" by ten
add eax, ecx ; add in current digit
jmp .top ; until done
.done:
ret
这超出了我的头脑并且可能有错误,但是“类似的事情”。它将停在以零结尾的字符串或以换行符结尾的字符串......或任何无效字符(您可能不想要)的末尾。修改以适应。
关于assembly - 将字符串转换为整数。使用 Nasm 的 x86 32 位汇编器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19461476/