I am trying to learn assembly language. Can someone explain and/or give an example of how to use addressing modes to access elements in each of the following array types?
-
array of
DWORD -
array of structures, where each structure contains two
DWORDs -
array of arrays, where each array has 10
DWORDs
You don’t mention which processor specifically you are targeting, but in 386+ this would work. I don’t have MASM, but MASM uses Intel syntax.
Let’s assume that
ebxis the base register andesiis the index register of the element. Standard 32-bit registers (eax,ebx,ecx,edx,ebp,esi,edi) are valid for the addressing mode used here.espcan be used as base register but not as index register. The value of index register can be optionally scaled with 2, 4 or 8. In this example we can use a scaling factor 4 for a dword array (in 386 legal scaling factors are 1, 2, 4 and 8).to read the value from array into
eax:mov eax, [ebx+4*esi]to store the value of
eaxinto array:mov [ebx+4*esi], eaxLet’s keep still
ebxas the base address. We can use a scaling factor 8 foresifor a struct array in which each struct consists of 2 dwords.to read the value of the first dword into
eax:mov eax, [ebx+8*esi]to store the value of
eaxinto first dword:mov [ebx+8*esi], eaxto read the value of the second dword into
eax:mov eax, [ebx+8*esi+4]to store the value of
eaxinto second dword:mov [ebx+8*esi+4], eaxIf the index can’t be hardcoded, you can just add 4 to
ebx(or whatever registers you use to store the base address). And if you have hardcoded base-address, then you could use eg.esito address the struct and eg.ebxto address the dword you want. Note that in 386+ you can’t scale more than one register (the index register) in indirect addressing.Let’s still assume you don’t know the base address of your array beforehand, and you’ll have it in
ebx, inesiyou have the index of the struct and inedxyou have the index of the dword.To get the address of the struct you can use
leamultiplication optimization (10 = 8 + 2):Edit: Fix:
lea esi,[4*esi](dword is 4 bytes)lea edi,[ebx+8*esi]lea edi,[edi+2*esi]Now you have the address of the struct in
edi. You just need to add the index of the dword (stored inedxin this example) multiplied by 4 (because each dword is 4 bytes).To read value of dword to
eax:mov eax,[edi+4*edx].To store value of
eaxinto dword:mov [edi+4*edx],eax.