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的跳跃,也适用于ecx
0,ecx
大于63组edx:eax
到0
。
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: