开发者

Difference between lea and offset

ar db "Defference $"

What's the difference between

mov dx,offset ar

and

lea dx,ar

I thin开发者_运维技巧k both are doing same work, but what is the difference between these two


In this use-case LEA and MOV do the same thing. LEA is more powerful than MOV if you want to calculate an address in a more complex way.

Lets for example say you want to get the address of the n'th character in your array, and the n is stored in bx. With MOV you have to write the following two instructions:

Mov dx, offset ar
add dx, bx

With lea you can do it with just one instruction:

lea dx, [ar + bx]

Another thing to consider here: the add dx,bx instruction will change the status flags of the CPU. The addition done inside the lea dx, [ar + bx] instruction on the other hand does not change the flags in any way because it is not considered an arithmetic instruction.

This is sometimes helpful if you want to preserve the flags while doing some simple calculations (address calculations are very common). Storing and restoring the flag-register is doable but a slow operation.


Quote from Assembly Language for x86 Processors, 7e, KIP R. IRVINE

It is not possible to use OFFSET to get the address of a stack parameter because OFFSET only works with addresses known at compile time. The following statement would not assemble:

mov esi,OFFSET [ebp-30]        ; error


You can use them to do the same thing but, LEA will always be better if the address is a little complex.

consider that you have the following array of chars:

ASC_TBL DB '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'

if you want to get the 6th element '5' you would do something like this using offset:

mov ax, offset ASC_TBL

add ax, 5h; flags [PF] will be affected 

On the other hand, if you are using the LEA instruction you can simply use one instruction like this:

LEA ax, [ASC_TBL + 5h]; no flags are affected

Notice that:

  • Although using LEA proved that it has an advantage over using offset, it's more efficient to use offset if the address isn't very complex to write or both of them will do the same thing with the same number of instructions. The reason is that offset ASC_TBL is calculated during translation - like being be preprocessed- but, LEA is an actual processor instruction.

  • you can't use the offset instruction to get the addresses that aren't known before the compilation time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜