1

I'm trying to take an array, add all the values in it, and then display them. Unfortunately for me, even though the following code builds, the output doesn't return the value which I am expecting.

For instance, one time when I ran it, I got

-2112902102

and another time I got

-1280521519

I'm assuming there's some sort of logic to that, but it doesn't exactly help me.

INCLUDE Irvine32.inc


.386
.stack 4096
ExitProcess proto,dwExitCode:dword

.data
array SBYTE 26, -81, -104, -57
total_sum SWORD ?

.code
main proc

mov esi, OFFSET array
mov ecx, LENGTHOF array
mov total_sum, 0
mov ebp,0

L1:
add ebp, [esi]
inc esi
loop L1

mov edx, ebp
call WriteInt
invoke ExitProcess,0

main endp
end main

And yes, I know that total_sum isn't doing anything at this point, but I first want to figure the rest out before implementing total_sum.

3
  • 2
    Don't you have a debugger which will let you step through the code, examine registers, etc ? Commented Nov 15, 2016 at 17:37
  • Yes I do. However, I'm having some slight issues figuring it out now. Commented Nov 15, 2016 at 17:40
  • 1
    Ask yourself this - how much data does that add instruction load from [esi] to add into ebp? Hint: it's not a single byte... Commented Nov 15, 2016 at 18:07

1 Answer 1

1

As you have been hinted, the problem is that you add dwords instead of bytes. The simple solution is to sign extend the byte into a temporary register before summing. That is replace this:

add ebp, [esi]

With:

movsx edx, byte ptr [esi]
add ebp, edx

And of course for printing you need to use eax, so change mov edx, ebp to mov eax, ebp. Or you could just use that to do the summing up directly.

Sign up to request clarification or add additional context in comments.

2 Comments

Much better solution than mine, more efficient, and thanks for pointing at my error (+1).
At one point I was thinking about if I needed to use a stack, although that was giving me issues. Thank you for showing me that I wasn't that far off from my original thinking.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.