Leonardo Cabbau
Leonardo Cabbau

Reputation: 21

Why i can't add in the array?

I'm trying to add the values in an array, and than make an avarage. But i notice that the values in array don't pass 256 when i make the sum.

SECTION .data   ;data section

array:      db  15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15
SIZE        EQU 20
    

;sum all positions of vector, length of 20

SECTION .text         ;code section

    global _start
    
    _start:

        xor bl,bl
        xor ecx,ecx
        jmp for_cond        
        
for_body:
        mov al,[array+ECX]
        add bl,al   
        inc ecx

for_cond:
        cmp ecx,SIZE
        jl  for_body    
        

        mov eax,1   ; exit command to kernel
        int 0x80    ; interrupt 80 hex, call kernel

Upvotes: 0

Views: 41

Answers (1)

zx485
zx485

Reputation: 29042

You try to add the whole sum in the BL register - which is only 8-bit wide and hence can only count up to 255. You better change your main loop to

for_body:
    movzx ax, byte [array+ECX]
    add   bx, ax   
    inc   ecx

This would realize the use of a 16-bit register that can count up to 65535. The MOVZX instruction will extend your 8-bit value from memory to a 16-bit value in AX. Then you can use a 16-bit register like BX or so to use for the final division by the number of elements (hold in CX or the constant SIZE).

Note:
If you use signed numbers instead of unsigned, you'd have to replace MOVZX by MOVSX.

Upvotes: 1

Related Questions