Search code examples
x86nasmaddressing-mode

What does "[V+ECX*2-2]" refer to in memory exactly?


So i have this exercise to solve: "Given a vector V of x 16 bit integers, check if the vector only contains even numbers. If it is the case, EAX will equal 1, otherwise 0. x is saved at the address n and has 16 bits. Here is the solution:

    MOVZX ECX, WORD [n]
    XOR EAX, EAX
bcle:
    TEST WORD [V+ECX*2-2], 1
    LOOPZ bcle
    JNZ sinon
    INC EAX
sinon:

Now i am stuck at [V+ECX*2-2]... maybe I am wrong but I believe the ECX register at this point contains a number which we are checking whether its even or not... and if thats the case why would we look for that address in memory? I have looked up on many websites and books how memory addressing works but I can never apply to exercises, maybe if someone here could explain to me with a simple example i would appreciate it...


Solution

  • ECX here contains an index (more precisely index+1) of current number in V array, not a number itself. It's index+1, because ECX was initialized with n (as in 1-based array, not with n-1 as in 0-based array) in MOVZX ECX, WORD [n].

    [V+ECX*2-2] - is calculating an address of the number indexed by ECX:

    • V - is an address of the array,
    • ECX*2 - is a calculating an offset to the ECX'th element in the array's memory, *2 - because we are dealing with 2-bytes numbers (16-bit)
    • -2 - is a changing 1-based-array-index into 0-based-array-index, as offset must be 0-based, again -2 because we're using 2-bytes numbers
    • [...] - is taking a value by the address inside brackets
    • WORD - taking a 2-bytes value

    Worth noting that V+...-2 is allowed because V - is a compile time constant, so compiler can calculate V-2 as another constant and put it into compiled binary. If V would be a dynamic value [V+...-2] would not fit into a single instruction, and the address need to be calculated separately.