1

作为 ASM 编程的初学者,我需要在汇编中得到 2 的 38 次方的结果,并且我需要你的帮助来理解为什么我的程序没有产生我需要的结果(它打印 4 个十进制):

.386
.model flat, stdcall
option casemap:none

include \masm32\include\windows.inc
include \masm32\include\msvcrt.inc
includelib \masm32\lib\msvcrt.lib

.data

formatstr db "%d",0

.code 
start:

mov eax , 2
mov ecx , 38
mov esi , eax
mov edx , 0

.while TRUE
    mul esi
    mov esi, edx
    add esi, eax
    mov edx, 0
    mov eax, 2
    dec ecx
    .break .if (!ecx)
.endw
    



invoke crt__cprintf, addr formatstr, esi


end start

如您所见,我正在使用 masm32 编写它(如果在这种情况下有任何问题)。

4

2 回答 2

8

2^38显然不适合一个 32 位寄存器,例如eax.

要存储值2^38( 274877906944),您需要 39 位。在 32 位代码中,您可以使用例如。两个 32 位寄存器,例如edx:eax. 但是,在 32 位代码中mul只接受 32 位因子(例如,寄存器,其他的总是eax),所以在循环中使用 32 位mul是行不通的,因为您不能将中间结果存储在 32 位中寄存器要再次相乘,即使mul将 64 位结果存储在edx:eax.

但是你可以rcl用来计算例如。2^38在 32 位代码中:

    xor edx,edx
    mov eax,2    ; now you have 2 in edx:eax
    mov ecx,38   ; 2^n, in this case 2^38 (any value x, 1 <= x <= 63, is valid).

x1: dec ecx      ; decrease ecx by 1
    jz ready     ; if it's 2^1, we are ready.

    shl eax,1    ; shift eax left through carry flag (CF) (overflow makes edx:eax zero)
    rcl edx,1    ; rotate edx through carry flag (CF) left
    jmp x1

ready:            ; edx:eax contains now 2^38.

编辑:受@Jagged O'Neill 的回答启发的非循环实现。这个没有指数> = 32的跳跃,指数< 32的跳跃,也适用于ecx0,ecx大于63组edx:eax0

    mov     ecx,38          ; input (exponent) in ecx. 2^n, in this case 2^38.
                            ; (any value x, 0 <= x <= 63, is valid).
; the code begins here.

    xor     eax,eax
    xor     edx,edx         ; edx:eax is now prepared.

    cmp     cl,64           ; if (cl >= 64),
    setb    al              ; then set eax to 0, else set eax to 1.
    jae     ready           ; this is to handle cl >= 64.

; now we have 0 <= cl <= 63

    sub     ecx,1
    setnc   al              ; if (count == 0) then eax = 0, else eax = 1.
    lea     eax,[eax+1]     ; eax = eax + 1. does not modify any flags.
    jna     ready           ; 2^0 is 1, 2^1 = 2, those are ready now.
    mov     ebx,ecx         ; copy ecx to ebx
    cmp     cl,32           ; if (cl >= 32)
    jb      low_5_bits
    mov     cl,31           ; then shift first 31 bits to the left.
    shld    edx,eax,cl
    shl     eax,cl          ; now shifted 31 bits to the left.
    lea     ecx,[ebx-31]    ; cl = bl - 31

low_5_bits:
    shld    edx,eax,cl
    shl     eax,cl

ready:
于 2012-10-01T22:18:14.773 回答
2

当您在 x86 上进行乘法运算时,edx将保留结果的前 32 位,eax并将保留结果的后 32 位。当你这样做时:

mul esi
mov esi, edx
add esi, eax

结果只有在 0 的情况下才有意义,edx所以mov/add基本上是在做mov esi, eax. 如果前 32 位非零,那么您最终会得到一个相当无意义的高位和低位混搭。

于 2012-10-01T20:15:50.993 回答