x86汇编的强大功能

Han*_* N. 0 x86 assembly exponent exponentiation masm32

作为ASM编程的入门者,我需要在Assembly中得到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
Run Code Online (Sandbox Code Playgroud)

你可以看到我用masm32写它(如果在那种情况下有任何问题).

谢谢.

nrz*_*nrz 8

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

要存储值2^38(274877906944),您需要39位.在32位代码中,您可以使用例如.两个32位寄存器,如edx:eax.但是,在32位代码中mul只接受32位因子(例如寄存器,其他的总是eax),因此mul在循环中使用32位将无法工作,因为您无法将中间结果存储在32位中即使存储64位结果,寄存器也会再次相乘.muledx: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.
Run Code Online (Sandbox Code Playgroud)

编辑:受@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:
Run Code Online (Sandbox Code Playgroud)