【问题标题】:x86-64 mul instruction does not multiply properly?x86-64 mul 指令不能正确乘法?
【发布时间】:2020-02-23 16:15:27
【问题描述】:

我在 x86-64 上的 MUL 指令遇到了奇怪的问题。似乎该指令没有正确地将寄存器中的 64 位内容相乘。我正在尝试编写一个简单的代码,将 2 提升到调用者定义的幂(传入RDI)。出于某种原因,RAX 中的值似乎卡在了一个神奇的 28 限制。我可能在这里再次遗漏了一些非常明显的东西(可能对指令本身有误解)。以下是我的代码和附加输出:

twotopwr:
    ;RDI contains the power
    CALL printfcall ;this prints the good value of 10 when testing with number 10 in RDI
    MOV RAX, 2;The 2 here
    PUSH RBX
    MOV RBX, 2;Multiplier
    CMP RDI, 0;If 0 then return 1
    JE ret1

loop:
    ;CALL printfcall
    DEC RDI ;Subtract the exponent
    CMP RDI, 0 ;Check if 0
    JE ret ;if 0 then return the value in rax
    MUL RBX ;Multiply rax by 2
    ;Print the rax content
    PUSH RDI
    MOV RDI, RAX
    CALL printfcall ;Debugging print
    POP RDI

    JMP loop ;Again
ret1:
    MOV RAX, 1;Exponent was 0
ret:
    POP RBX
    ;return value in rax
    RET

输出

The int is 10
The int is 4
The int is 26
The int is 28
The int is 28
The int is 28
The int is 28
The int is 28
The int is 28
The int is 28

我的打印功能:

printfcall:;Pass in RDI

        MOV RSI, RDI
        PUSH RDI
        MOV RDI, formatStrdec
        MOV AL, 0 
        CALL printf
        POP RDI
        RET

【问题讨论】:

  • 看起来你将printfcall设为函数而不是宏的唯一好处是,如果你在没有先压入任何东西的情况下调用它,它有时会将堆栈对齐16 .

标签: assembly printf x86-64 multiplication


【解决方案1】:

printf 将返回在RAX 寄存器中打印出的字符数,在首先打印此The int is 4 之后为 13,这就是为什么您在下一次迭代中得到 26 并且该迭代 printf 返回 14 为书写的字符数,乘以 2 后为 28,并且如此反复。

【讨论】:

  • 另外,不要将MUL 循环用于2 的幂。只需使用班次;)
  • @Jester 哦,你是完全正确的,当我让这个第一个工作时,将使用左移来实现这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
相关资源
最近更新 更多