Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

assembly - Convert string to int. x86 32 bit Assembler using Nasm

So I'm trying to convert a string to a number so I can add another number to it later. here is what I have to far in my .text for the conversion. num2Entered is what the user entered. Num1plusNum2 is the label that I will eventually add to. They are both declared in the .bss section. Any help would be appreciated!

    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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Each character is only a single byte, but you probably want to add it to a larger result. Might as well go for 32 bits... (can hobble your routine to 16 bits if you really want to)

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

That's off the top of my head and may have errors, but "something like that". It'll stop at the end of a zero-terminated string, or a linefeed-terminated string... or any invalid character (which you may not want). Modify to suit.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...