8086汇编程序存储唯一值

8086 assembly program to store unique values

我一直在制作这个程序,它接受一个列表并在其中找到独特的元素并将其存储在另一个列表或寄存器中

下面的代码将主列表放入 SI 寄存器,然后 BX 作为指针遍历整个数组以找到相似之处...如果没有找到相似之处,则在 SI 中找到元素(存储在 AL 中)存储在 DI 中。为了避免当 BX 到达与其值完全相同的位置时可能发生的第一个相似性,我为此设置了一个标志。


uniqueElement macro list1 list2
    local loop1,comparasionLabel,checkFlag,trigger,nextElement,addElement,endAddition
    lea si,list1
    lea di,list2 
loop1:
    mov ah,00H
    mov cx,00H   ;this is an intial flag gets triggered when an initial similarity is spotted
    lea bx,list1  ; this will be the search loop which will compare each of it's elements to SI
    mov al,BYTE PTR[SI] 
    cmp al,'$'  ; since I'm using a '$' terminated string
        je endAddition
comparasionLabel:
    mov dl,BYTE PTR[BX]
    cmp dl,'$'
        je addElement
    cmp al,dl
        je checkFlag
    inc bx
    jmp comparasionLabel    
            
checkFlag:           
    cmp cx,00H    ; this is when a first similarity is spotted, the flag gets triggered here
        je trigger
    cmp cx,01H       ; or if it was already triggered and another similarity spotted, SI moves to next element
        je nextElement     
trigger:
    mov cx,01H
    inc bx
    jmp comparasionLabel
nextElement:
    inc si
    jmp loop1
addElement:
    mov ah,00h
    mov BYTE PTR [di],al
    inc di
    inc si
    jmp loop1        
        
endAddition:
    inc di
    mov ah,00H
    mov al,'$'
    mov BYTE PTR[di],al               
endm


这只是执行宏的代码

.model small
.data
list1 db 'H3llo$'    
list2 db 50 DUP [?]
.code  
mov ax,@data
mov ds,ax
uniqueElement list1 list2
mov ah,09H
mov dx,offset di
int 21h

.exit

我不知道为什么它一直打印相同的列表而不删除唯一项

and I have no Idea why it keeps printing the same list without removing the unique items

mov ah,09H
mov dx,offset di
int 21h

打印错误。指令mov dx,offset di不正确!如果它会让 MASM 加载 DX 寄存器为零,我不会感到惊讶,因为源文本的偏移地址为零,结果将是:

h3llo

正确的代码如下:

mov  dx, offset list2
mov  ah, 09h
int  21h

代码的其余部分是正确的,除了一个无关的 inc di 在终止“$”之前在输出字符串中引入了一个垃圾字符。


下面是我重写的你的算法,删除了很多冗余。
我采用了另一种方法,因为我没有 标记 相似性,而是 计数 匹配。每个唯一字符都会产生一个匹配项,因此只有当计数器具有 CX=1.

时,才会将一个字符添加到输出缓冲区
    lea  si, list1
    lea  di, list2 
loop1:
    mov  al, [si] 
    cmp  al, '$'
    je   endAddition

    xor  cx, cx       ; Counts matches, will become at least 1
    lea  bx, list1
loop2:
    inc  bx
    mov  dl, [bx-1]
    cmp  dl, '$'
    je   maybeAddElement
    cmp  al, dl
    jne  loop2
    inc  cx
    jmp  loop2

maybeAddElement:
    cmp  cx, 1
    jne  nextElement
    mov  [di], al
    inc  di
nextElement:
    inc  si
    jmp  loop1        
        
endAddition:
    mov  [di], al      ; AL='$'