简体   繁体   中英

Assembly How to translate IMUL opcode (with only one oprand) to C code

Say I got

EDX = 0xA28

EAX = 0x0A280105

I run this ASM code

IMUL EDX

which to my understand only uses EAX.. if one oprand is specified

So in C code it should be like

EAX *= EDX;

correct?

After looking in debugger.. I found out EDX got altered too.

0x0A280105 * 0xA28 = 0x67264A5AC8

in debugger

EAX = 264A5AC8 EDX = 00000067

now if you take the answer 0x67264A5AC8 and split off first hex pair, 0x67 264A5AC8 you can clearly see why the EDX and EAX are the way they are.

Okay so a overflow happens.. as it cannot store such a huge number into 32 bits. so it starts using extra 8 bits in EDX

But my question is how would I do this in C code now to get same results?

I'm guessing it would be like

EAX *= EDX;
EDX = 0xFFFFFFFF - EAX; //blah not good with math manipulation like this.

The IMUL instruction actually produces a result twice the size of the operand (unless you use one of the newer versions that can specify a destination). So:

imul 8bit -> result = ax, 16bits
imul 16bit -> result = dx:ax, 32bits
imul 32bit -> result = edx:eax, 64bits

To do this in C will be dependent on the compiler, but some will work doing this:

long result = (long) eax * (long) edx;
eax = result & 0xffffffff;
edx = result >> 32;

This assumes a long is 64 bits. If the compiler has no 64 bit data type then calculating the result becomes much harder, you need to do long multiplication.

You could always inline the imul instruction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM