首页 > 解决方案 > 在汇编 nasm 32 位中单独访问输入的每个字符

问题描述

所以我的输入是一个包含字母 AZ 和数字 0-9 的 9 个字符的长代码。

每个字符都有不同的数学运算,例如 647388ABC 中的字符 1 (6) 将乘以 5,(4) 将乘以 2 等等。

所有结果将在稍后进行总结,但首先我需要能够单独访问它们。

mov eax, [esp+8] ; this gives me the input in eax 
mov ebx, [eax+4] ; code into ebx

我现在的想法就是这样做:

mul [ebx+1], 5

然后继续直到我到达最后一个字符,但它似乎不起作用

标签: assemblyx86nasmintel32-bit

解决方案


你输入的字符是字符串的形式吗?如果是这样,则必须将每个字符单独转换为整数。您没有指定每个整数是任意单个数字还是以 10 为底的倍数。“123”只是 1、2、3 还是 123(一百二十三)?

mul 指令使用 al、ax 或 eax 寄存器并将结果存储在 ax、dx:ax 或 edx:eax(高位:低位)中。但更方便的是imul:您可以将它与立即操作数一起使用,并且只产生与输入宽度相同的输出。

lea   ecx,[esp+8] ;ecx points to input (647388ABC)

movzx eax, byte [ecx] ;get a single byte from ecx and move it into al
sub   eax, 48         ; ASCII digit -> integer.  48 = '0'
imul  eax, 5          ; result 5*6 is stored in eax

要处理字母,您需要在子结果 <= 9(无符号)上进行分支,否则减去另一个数量。

扩展:假设 eax 已经保存了这个字节,我们可以做一个分支来检查它是否是一个来自 "A" - "Z" 的字符,其中 "A"==0 && "Z"==25 然后执行必要的操作(减法)到获取整数。

cmp eax,65
jl digit
cmp eax,90
jg terminate
sub eax,65
jmp operation
digit:
sub eax,48
operation:
                ;perform mathematical operation here
terminate:
ret

推荐阅读