Return difference between major and minor array values in Assembly

1

I'm trying to make a code in assembly with arq. x86 using NASM.

In this code I should return the difference between the highest value and lowest value of an array, as below.

However, while rolling it is returning 14 for the example below and the correct one would be 18 (20-2). Could you help me find my mistake? Thank you very much in advance.

section .data
    array: DB 2,4,6,8,10,12,14,16,18,20
    size EQU $-array

section .text

global _start
_start:

    mov eax,[array]
    mov ebx,[array]

    xor ecx,ecx
    mov edx,size

jmp compara

maior:
    mov eax,[array+ecx]
    jmp volta_maior

menor:
    mov ebx,[array+ecx]
    jmp volta_menor

compara:
    cmp ecx,edx
    jnle fim
    cmp [array+ecx],eax
    jge maior
volta_maior:
    cmp [array+ecx],ebx
    jle menor
volta_menor:
    inc ecx
    jmp compara

fim:

    sub eax,ebx
    mov ebx,eax
    mov eax,1
    int 0x80
    
asked by anonymous 17.06.2018 / 21:52

1 answer

2

There are 2 problems with the program:

Since the array consists of bytes, all operations with the data (load, comparisons, etc.) must be done with 8-bit registers and not 32. Example:

_start:

    mov al,[array]      ; carrega o registrador al (8 bits) com o valor [array]
    mov bl,[array]      ; carrega o registrador bl (8 bits) com o valor [array]
    ...
The end of looping should occur when ecx is equal to (or greater than) edx :

compara:
    cmp ecx,edx
    jge fim                 ; Executa até que ecx >= edx
    cmp [array+ecx],eax
    jge maior

The modified program (with looping corrected and registers switched to 8-bit registers) looks like this:

section .data
    array: DB 2,4,6,8,10,12,14,16,18,20
    size EQU $-array

section .text

global _start
_start:

    mov al,[array]
    mov bl,[array]

    xor ecx,ecx
    mov edx,size

    jmp compara

maior:
    mov al,[array+ecx]
    jmp volta_maior

menor:
    mov bl,[array+ecx]
    jmp volta_menor

compara:
    cmp ecx,edx
    jge fim
    cmp [array+ecx],al
    jge maior

volta_maior:
    cmp [array+ecx],bl
    jle menor

volta_menor:
    inc ecx
    jmp compara

fim:
    sub al,bl
    movzx ebx,al
    mov eax,1
    int 0x80

After execution:

~/$ ./a.out
~/$ echo $?
18
~/$
    
17.06.2018 / 23:58