首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 內嵌組合語言入門(23):LOOP 指令實作冪運算

     編輯:Delphi

LOOP 指令

LOOP label:DEC ECX;若 ECX != 0 則跳轉到 label。ECX 為隱含計數器。

計算 x^n (x 的 n 次方)

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)。
  • 現代 CPU 上 loop 指令較慢(微碼實作),高效能場合建議手寫 dec ecx; jnz label。

改進:支援 n=0 返回 1

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 即為結果
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved