Find middle value of a list

639 Views Asked by At

I'm having trouble figuring out how to find the middle value in a list of double words that has an even amount of 50 numbers. When I try to implement my code as follows

mov eax, dword[volumes+100]
add eax, dword[volumes+104]
div dword[saTwo]
mov dword[vMid], eax

where volumes 100 and 104 are the 25th and 26th elements in the list. I then divide by two and store the middle value in vMid. The problem arises when I debug the program vMid is 0 which is definitely not correct.

2

There are 2 best solutions below

0
On

The trouble likely has to do with EDX though you may not realize it at first. :)

In the x86 instruction set the size of the DIV is determined by the operands, as you would expect. However, by specifying a 32 bit divide with your DWORD PTR the processor will automatically attempt to divide like so: EDX:EAX / DWORD [saTwo]. EAX represents the least significant portion of the dividend. If EDX happens to have a relatively large value in it then the resulting quotient will likely be zero with a remainder sitting in EDX.

You will want to clear EDX first and then perform your DIV

0
On

Don't DIV. Use right shift instead.

If the numbers are unsigned, the carry flag contains the overflow, so use RCR. Otherwise SAR. If speed is an issue, check combinations of clearing carry flag and RCR.