将字符串转换为int。使用Nasm的x86 32位汇编程序

时间:2013-10-19 01:51:54

标签: assembly x86 integer nasm

所以我正在尝试将字符串转换为数字,以便稍后我可以添加另一个数字。这是我在转换中使用的文本。 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

3 个答案:

答案 0 :(得分:2)

每个字符只是一个字节,但您可能希望将其添加到更大的结果中。不妨去寻找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

这是我的头脑,可能有错误,但“有类似的东西”。它将在零终止字符串或换行终止字符串...或任何无效字符(您可能不需要)的末尾停止。修改以适应。

答案 1 :(得分:1)

"123"
 |||     val = 0
 |||______ val = val + ('3' - 48) * 10power0       [val now is 3]
 ||_______ val = 3   + ('2' - 48) * 10power1       [val now is 23] 
 |________ val = 23  + ('1' - 48) * 10power2       [val now is 123]

note: ascii of '1' means 49, '2' means 50 and so on

答案 2 :(得分:0)

or we can say:
"123"  -> starting from 1

1 + 0 * 10  = 1
2 + 1 * 10  = 12
3 + 12 * 10 = 123

This will match to atoi function as below:

atoi:

push    %ebx        # preserve working registers
push    %edx
push    %esi

mov $0, %eax        # initialize the accumulator
nxchr:
    mov $0, %ebx        # clear all the bits in EBX
    mov (%esi), %bl     # load next character in BL
    inc %esi            # and advance source index

    cmp $'0', %bl       # does character preceed '0'?
    jb  inval           # yes, it's not a numeral jb:jump below
    cmp $'9', %bl       # does character follow '9'?
    ja  inval           # yes, it's not a numeral ja:jump above

    sub $'0', %bl       # else convert numeral to int
    mull ten            # multiply accumulator by ten. %eax * 10
    add %ebx, %eax      # and then add the new integer
    jmp nxchr           # go back for another numeral

inval:
   pop  %esi            # recover saved registers
   pop  %edx
   pop  %ebx
   ret

希望这会有所帮助。