[英]Assembly x86 append numbers to a variable
我正在读取输入的数字字符串,逐个字符地对其进行迭代以将每个数字转换为十进制。
现在在我的一个寄存器(例如AL
中的每次迭代中,我都有一位数字,假设
Input: 12345678
Iteration_1 : 1
Iteration_2 : 2
...
Iteration_8 : 8
我想将这些整数添加到DD
变量中,以便在迭代结束时我将拥有一个DD
变量,其中包含我可以用于操作的整数。
有这种感觉吗? 如何在每次迭代时将当前数字附加到DD变量?
将寄存器清零以用作“到目前为止的结果”。
最佳:
得到一个角色。
确保您确实有一个有效的十进制数字。
减去“ 0”可将字符转换为数字。
将“到目前为止的结果”乘以十。
添加新号码。
转到顶部。
这就是我用的...
;--------------------
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
;------------------------
现在只是mov [myvar], eax
。 这有一些缺点! 我只是退出任何无效字符。 这捕获了一个以零结尾的字符串,或一个以换行符结尾的字符串(从Linux中获取),或者其他任何东西。 很好,但是如果他们搞砸了,我就不会对用户大吼大叫。 我也不能检查溢出。 如果需要,请抛弃“可爱的把戏”,然后使用imul eax, 10
。如果您不需要处理负数,则可以简化一点。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.