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奥尼尔的回答启发非循环的实现。这一个是不跳跃为指数> = 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:
什么是“不起作用?” – GManNickG
@GManNickG编辑 –
想想存储2^38需要多少个数字,以及结果寄存器有多少位。 – JohnTortugo