gpt4 book ai didi

assembly - 将两个数字放入 EAX 寄存器

转载 作者:行者123 更新时间:2023-12-04 06:17:12 28 4
gpt4 key购买 nike

我试图将两个 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

最佳答案

像这样:

; 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

这样做的原因是 axeax 的 16 个最低有效位.更多详情请见 this所以问题和接受的答案。此方法也适用于 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 扩展大小.

关于assembly - 将两个数字放入 EAX 寄存器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7077585/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com