assembly - 两个数组的总和,每个数组 n 个字节

标签 assembly emu8086 x86-16

这是我的解决方案,我想知道它是否正确以及解决它的另一种方法

include 'emu8086.inc'
org 100h

mov CX,n
lea SI,a
mov AL,0

start_sum_a:         ;sum all the n elements of the first array
add AL, [SI] 
inc SI
loop start_sum_a

mov CX,n
lea SI,b 

start_sum_b:        ;sum all the n elements of the 2nd array to 
add AL, [SI]        ;the first sum
inc SI
loop start_sum_b

call print_num      ;print the sum

ret

a db 1,3,5,7,9,11,13,15,17,18
b db 0,2,4,6,8,10,12,14,16,19
n dw 10

DEFINE_PRINT_NUM
DEFINE_PRINT_NUM_UNS

最佳答案

i'd like to know if it's correct

您的解决方案看起来不错,尽管我有预感“emu8086.inc”中定义的函数print_num更希望得到AX寄存器中的数字。因此,最好将 mov AL,0 指令更改为 xor ax,ax,这将清除整个 AX 寄存器,而不仅仅是其低字节 >AL.

what is another way of solving it

如果为两个数组设置单独的指针,则可以选择在单个循环中完成工作。

    lea  si, a
    lea  di, b
    mov  cx, n
    xor  ax, ax
start_sum:
    add  al, [si]        ;Element of a array
    add  al, [di]        ;Element of b array
    inc  si
    inc  di
    loop start_sum

但是由于这些数组的起始点在内存中相距一定距离 (10),因此有一个仅使用 1 个指针的解决方案:

    lea  si, a
    mov  cx, n
    xor  ax, ax
start_sum:
    add  al, [si]        ;Element of a array
    add  al, [si + 10]   ;Element of b array
    inc  si
    loop start_sum

最后,由于这些数组在内存中相邻,因此循环可以更简单。只需将迭代次数加倍即可(Peter Cordes 的建议之一):

    lea  si, a
    mov  cx, n
    shl  cx, 1           ;Double the counter
    xor  ax, ax
start_sum:
    add  al, [si]        ;Element of a array or b array
    inc  si
    loop start_sum

关于assembly - 两个数组的总和,每个数组 n 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45900051/

相关文章:

assembly - 8085汇编指令MOV、LDA和STA

assembly - 在 ARM 中使用 STREXEQ 代替 STREX 进行自旋锁实现

assembly - 如何在 Assembly 中获取实时按键?

assembly - EMU 8086 在寄存器中存储错误的数组元素值

assembly - 如何将数字类型位置转换为x,y类型位置?

c - m68k-elf 目标是否支持 GCC 内联 asm goto?

assembly - 像 .size X,.-X 这样的代码模式有什么作用?

assembly - 删除屏幕上的一个字符

assembly - 使用 SHR 指令除以 8

c - Dosbox 是模拟 32 位环境还是 16 位环境?