简体   繁体   中英

Assembly x86 append numbers to a variable

I'm reading an input numeric string, iterate it character by character to convert each digit in decimal.

Now at every iteration in one of my register, example AL , i have the single digit, let's say

Input: 12345678
Iteration_1 : 1
Iteration_2 : 2
...
Iteration_8 : 8

I would like to add these integers to a DD variable, so that at the end of the iteration i would have a DD variable containing the whole number that i could use for operation.

Has this sense? How could i append at each iteration the current number to the DD variable?

Zero out a register to use as a "result so far".

top:

Get a character.

Make sure you really have a valid decimal digit.

Subtract '0' to convert a character to a number.

Multiply "result so far" by ten.

Add in the new number.

Go to top.

This is what I use...

;--------------------
atoi:
; expects: address of string on stack
; returns: number in eax
; "trashes" ecx and edx
; actually, edx is "next character"
; and ecx (cl) is the "invalid" character
; think of "192.168.0.1"...
; caller cleans up stack
push ebx

mov edx, [esp + 8]  ; pointer to string
xor ebx, ebx ; assume not negative

cmp byte [edx], '-'
jnz .notneg
inc ebx ; indicate negative
inc edx ; move past the '-'
.notneg:

xor eax, eax        ; clear "result"
.top:
movzx ecx, byte [edx]
inc edx
cmp ecx, byte '0'
jb .done
cmp ecx, byte '9'
ja .done

; we have a valid character - multiply
; result-so-far by 10, subtract '0'
; from the character to convert it to
; a number, and add it to result.

lea eax, [eax + eax * 4]
lea eax, [eax * 2 + ecx - '0']

jmp short .top
.done:
test ebx, ebx
jz .notminus
neg eax
.notminus:
pop ebx
ret
;------------------------

Now just mov [myvar], eax . This has some disadvantages! I just quit on any invalid character. This catches a zero-terminated string, or a linefeed-terminated string (as I get from Linux), or whatever. Fine, but I don't get to yell at the user if they screw up. Also I can't check for overflow. If you need that, ditch the "cute trick" and go with imul eax, 10 ... If you don't need to deal with negative numbers, it can be simplified a bit.

MOV CX, #8
loop:
MOV DX, #1
ADDS AX, DX
ADDS DX, #1
SUBS CX, CX, #1         
BNE loop  
DD dw 0  
MOV DD, AX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM