将两个数字放入EAX寄存器

时间:2011-08-16 11:37:01

标签: assembly nasm cpu-registers

我试图将两个16位数字与以下NASM代码相乘:

mov ax, [input1]
mov bx, [input2]
mul bx

以前代码的结果存储在DX:AX

我尝试使用单独的库“print_int”中的函数将整数打印到屏幕上。但是print_int要求整数必须在EAX寄存器中。

如何将32位整数放入EAX寄存器?

更新

我想出了这个

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

2 个答案:

答案 0 :(得分:2)

像这样:

; Before: 
; Result is in DX:AX on the form ABCD:EFGH
; EAX = ????EFGH : AX contains EFGH, upper part of EAX has unknown content
; EDX = ????ABCD : DX contains ABCD (the 16 most siginficant bits 
;                                   of the multiplication result) 
;                                   like with EAX the upper (=most siginifcant) 
;                                   16 bits of EDX also has unknown content.

and eax, 0x0000ffff ; clear upper bits of eax
; EAX = 0000EFGH

shl edx, 16 ; shift DX into position (will just shift the upper 16 junk bits away)
; EDX = ABCD000

or eax, edx ; combine in eax
; EAX = ABCDEFGH

这有效的原因是ax指的是eax的16个最低有效位。更详细的信息请参阅this SO问题和接受的答案。此方法也适用于imul,但通常在处理汇编代码中的有符号数时必须小心。

一个完整的例子:

    bits 32

    extern printf
    global main

    section .text
main:
    push ebx
    mov ax, 0x1234
    mov bx, 0x10
    mul bx
    and eax, 0x0000ffff ; clear upper bits of eax
    shl edx, 16 ; shift DX into position
    or eax, edx ; and combine
    push eax
    push format
    call printf
    add esp, 8
    mov eax, 0
    pop ebx
    ret

    section .data
format: db "result = %8.8X",10,0

编译:

nasm -f elf32 -g -o test.o test.asm
gcc -m32 -o test test.o

更新

在32位计算机上,如果在上下文中合理,则通常更容易且更可取处理32位值。例如:

    movzx eax, word [input1] ; Load 16-bit value and zero-extend into eax
    movzx edx, word [input2] ; Use movsx if you want to work on signed values
    mul eax, edx ; eax *= edx

其中还显示了一种更新,更易于使用的mul指令的用法。您也可以按照现在的标准mov ax, [input1]进行操作,然后再使用movzx eax, ax扩展尺寸。

答案 1 :(得分:1)

最短的路是......

asm
//load test values in eax and exb
        mov     eax,    $00000102
        mov     ebx,    $00000304
//merge ex and bx to eax
        shl     ebx, 16
        shld    eax, ebx, 16
end;

导致eax = $ 01020304

我想要oposite然后......

asm
//load test values in eax and exb
        mov     eax,    $00000102
        mov     ebx,    $00000304
//merge ex and bx to eax
        shl     eax, 16
        shrd    eax, ebx, 16
end;

结果是eax = $ 03040102