在 AT&T 汇编中从 ascii 转换为整数
Convert from ascii to integer in AT&T Assembly
如何将 ascii 码转换为整数?
data
asd:
.int 32
.text
.globl _start
_start:
movl , %eax
movl , %ebx
movl ,(asd)
add ,(asd)
movl $asd, %ecx
movl , %edx
int [=10=]x80
# Exit the program
movl , %eax
movl [=10=], %ebx
int [=10=]x80
代码正在写一个ascii值,我想如果我能把48加到这个值上。我会写,但我不会打印,一个两阶段的数字"for example 53 or 156"。如何打印?
通常最好先考虑高级语言版本。如果数字有 n
位并且存储在数组 a
中,那么我们需要:
char *p = a;
unsigned val = 0;
while (n > 0) {
n--;
val = 10 * val + (*p++ - '0');
}
所以假设 %esi
是 p
,%eax
是 val
,%ecx
是 n
。
逐行翻译以使其尽可能简单和直白:
movl $n, %ecx
movl $a, %esi
xorl %eax, %eax # val = 0
eval_while_cond:
testl %ecx, %ecx # if (n <= 0)
jle done # goto done
subl , %ecx # n--
movl %eax, %ebx # tmp1 = val
imul , %ebx # tmp1 = 10 * tmp1
movzbl (%esi), %eax # tmp2 = *p
addl , %esi # p++
subl $'0, %eax # tmp2 = tmp2 - '0'
addl %eax, %ebx # val = tmp2 + tmp1
jmp eval_while_cond
done:
# result is now in %eax
请注意,这只是获取函数式汇编语言的通用方法。这没有以任何方式优化。获得最佳性能所需的技巧完全是另一个话题。
其他选项是使用编译器(例如 https://godbolt.org/z/WzGYjePzx) with light optimization like -O1, -Og, or -Os to get somewhat-readable asm (although in this case they use not-totally-obvious tricks with LEA to multiply by 10 and subtract '0'
(48
), or they make a mess with weird loop conditions.) See also
如何将 ascii 码转换为整数?
data
asd:
.int 32
.text
.globl _start
_start:
movl , %eax
movl , %ebx
movl ,(asd)
add ,(asd)
movl $asd, %ecx
movl , %edx
int [=10=]x80
# Exit the program
movl , %eax
movl [=10=], %ebx
int [=10=]x80
代码正在写一个ascii值,我想如果我能把48加到这个值上。我会写,但我不会打印,一个两阶段的数字"for example 53 or 156"。如何打印?
通常最好先考虑高级语言版本。如果数字有 n
位并且存储在数组 a
中,那么我们需要:
char *p = a;
unsigned val = 0;
while (n > 0) {
n--;
val = 10 * val + (*p++ - '0');
}
所以假设 %esi
是 p
,%eax
是 val
,%ecx
是 n
。
逐行翻译以使其尽可能简单和直白:
movl $n, %ecx
movl $a, %esi
xorl %eax, %eax # val = 0
eval_while_cond:
testl %ecx, %ecx # if (n <= 0)
jle done # goto done
subl , %ecx # n--
movl %eax, %ebx # tmp1 = val
imul , %ebx # tmp1 = 10 * tmp1
movzbl (%esi), %eax # tmp2 = *p
addl , %esi # p++
subl $'0, %eax # tmp2 = tmp2 - '0'
addl %eax, %ebx # val = tmp2 + tmp1
jmp eval_while_cond
done:
# result is now in %eax
请注意,这只是获取函数式汇编语言的通用方法。这没有以任何方式优化。获得最佳性能所需的技巧完全是另一个话题。
其他选项是使用编译器(例如 https://godbolt.org/z/WzGYjePzx) with light optimization like -O1, -Og, or -Os to get somewhat-readable asm (although in this case they use not-totally-obvious tricks with LEA to multiply by 10 and subtract '0'
(48
), or they make a mess with weird loop conditions.) See also