【发布时间】:2021-12-26 15:37:17
【问题描述】:
我对组装非常陌生,并且在使用不同长度数字进行基本计算时遇到困难。
这是我的添加代码,适用于长度为 3 个或更少字符的数字。只要两者的长度相同。例如 123 + 123 工作正常并输出 246。但 12 + 123 不起作用,它输出 253 作为答案。 我如何才能使用不同的长度数字来实现它?
sys_exit equ 1
sys_read equ 3
sys_write equ 4
stdin equ 0
stdout equ 1
section .data
newLine db 10
cquestion db 'Enter a number: ', 0xa
cqLen equ $ - cquestion
answer db 'Your answer is: '
aLen equ $ - answer
section .bss
number1 resb 4
number2 resb 4
number1Len resd 1
number2Len resd 1
answ resb 8
%macro write_string 2
mov eax, 4
mov ebx, 1
mov ecx, %1
mov edx, %2
int 0x80
%endmacro
section .text
global _start
_start:
write_string cquestion, cqLen
mov eax, sys_read
mov ebx, stdin
mov ecx, number1
mov edx, 4
int 0x80
mov [number1Len], eax
write_string cquestion, cqLen
mov eax, sys_read
mov ebx, stdin
mov ecx, number2
mov edx, 4
int 0x80
mov [number2Len], eax
write_string answer, aLen
clc
mov ecx, [number2Len] ;number of digits
dec ecx ;need to decrease one for some reason?
mov esi, ecx
dec esi ;pointing to the rightmost digit.
.add_loop:
mov al, [number1 + esi]
adc al, [number2 + esi]
aaa
pushf ; also no idea what this is here for
or al, 30h ; or this
popf ; and this...
mov [answ + esi], al
dec esi
loop addition.add_loop
mov eax, sys_write
mov ebx, stdout
mov ecx, answ
mov edx, 8
int 0x80
mov eax, sys_write
mov ebx, stdout
mov ecx, newLine
mov edx, 1
int 0x80
mov [answ], DWORD 0
【问题讨论】:
-
"出于某种原因需要减少一个?" - 最后摆脱换行符。
pushf/popf是为下一次迭代保留进位标志的值。or al, 30h正在通过添加0的 ascii 代码转换为文本。要处理不同的长度,只需假装较短的用零填充。 -
一次做 1 个数字是非常低效的。特别是使用
pushf/or/popf而不是lea eax, [eax + 0x30],如果0x30位始终未设置开始。
标签: linux assembly x86 nasm bigint