Im trying to multiply two 16 bit numbers with the following NASM codes:
mov ax, [input1]
mov bx, [input2]
mul bx
The result of the previous codes is stored in DX:AX
Im trying to print the integer to the screen using a function from a separate library “print_int”. But print_int requires that the integer must be in the EAX register.
How can i put the 32-bit integer in the EAX register?
Update
I came up with this
mov cx, dx ;move upper half(16 bits) of result in cx
shl ecx, 16 ;shift the contents of ecx 16 bits to the left
mov cx, ax ;move lower half(16 bits) of result in cx
Like this:
The reason why this works is that
axrefers to the 16 least significant bits ofeax. Fore more detail see this SO question and the accepted answer. This method will also work forimul, but usually you have to be careful when dealing with signed numbers in assembly code.A complete example:
Compile with:
Update:
On 32-bit machines it is usually easier and preferable to deal with 32-bit values if it is reasonable in the context. For example:
Which also shows the usage of one of the newer, easier to use,
mulinstructions. You can also do as you’re doing now andmov ax, [input1]and then later extend the size withmovzx eax, ax.