LOOP label:DEC ECX;若 ECX != 0 則跳轉到 label。ECX 為隱含計數器。
function Power(x, n: Integer): Integer;
asm
// EAX 已含 x (參數1)
mov ecx, n // 參數2 → ECX (計數器)
sub ecx, 1 // 已有一個 x 在 EAX,需再乘 n-1 次
@LoopLabel:
imul eax, eax // 有號乘法:EAX := EAX * EAX
loop @LoopLabel // DEC ECX; JNZ @LoopLabel
end;
註:imul eax, eax 為 32位有號乘法,結果存回 EAX。若溢位高 32 位丟失。
procedure TForm1.Button1Click(Sender: TObject);
begin ShowMessage(IntToStr(Power(2, 10))); // 1024 end;
ECX 必須預先載入循環次數。asm 區塊內必須加 @ 前綴(如 @LoopLabel),或使用 Delphi 標號語法。loop 相當於 dec ecx; jnz label,但指令碼更短 (2 bytes)。loop 指令較慢(微碼實作),高效能場合建議手寫 dec ecx; jnz label。function Power(x, n: Integer): Integer;
asm
test ecx, ecx
jz @ret1
mov ecx, n
sub ecx, 1
@LoopLabel:
imul eax, eax
loop @LoopLabel
ret
@ret1:
mov eax, 1
end;
mul eax // 無號乘法:EDX:EAX := EAX * EAX,結果 64 位
; 若只需低 32 位,mul 後 EAX 即為結果