|
MKoD - D Programming Language
An ASM Factorial Example in D - code-name asm_example2.d
An ASM Factorial Example:
// asm_example2.d - last tested with D v1.0
/+
' A assembly example for finding factorials numbers between 0 to 12.
'
' Example: 7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040
'
' To Compile: C:\dmd\MKoD_ex>dmd asm_example2.d
+/
module factorial;
private import std.stdio;
// comment out the below statement to hide the main() function.
debug = factorial;
uint factorial( in uint uiNum )
{
uint uiFactorial;
asm
{
mov EAX,[ uiNum ]; // EAX = uiNum
cmp EAX,12; // if EAX <= 12
jbe _inittest; // then goto _inittest
mov EAX,0; // set as 0 to point out an error
jmp _exit; // return 0 as an error
_inittest:
cmp EAX,1; // if EAX > 1
jg _initecx; // then goto _initecx
mov EAX,1; // 0 or 1 becomes 1
jmp _exit; // return 1
_initecx:
mov ECX,EAX; // ECX = counter
_dececx:
dec ECX; // ECX = n - 1
mul ECX; // EAX = n * (n - 1)
cmp ECX,1; // if counter > 1
ja _dececx; // then continue to _dececx
_exit:
mov [ uiFactorial ],EAX; // uiFactorial = EAX's value
}
if ( uiFactorial == 0U )
throw new Exception( "The parameter value passed in is greater than 12." );
return uiFactorial;
} // end uint factorial( in uint uiNum )
debug( factorial )
{
void main()
{
writefln( "Factorials from 0 to 12 done in x86 Assembly." );
for ( uint uix = 0U; uix < 13U; uix++ )
{
writefln( "factorial( %2d ) = %d", uix, factorial( uix ) );
}
} // end void main()
}
C:\dmd\MKOD_ex>dmd asm_example2.d
C:\dmd\bin\..\..\dm\bin\link.exe asm_example2,,,user32+kernel32/noi;
C:\dmd\MKOD_ex>asm_example2
Factorials from 0 to 12 done in x86 Assembly.
factorial( 0 ) = 1
factorial( 1 ) = 1
factorial( 2 ) = 2
factorial( 3 ) = 6
factorial( 4 ) = 24
factorial( 5 ) = 120
factorial( 6 ) = 720
factorial( 7 ) = 5040
factorial( 8 ) = 40320
factorial( 9 ) = 362880
factorial( 10 ) = 3628800
factorial( 11 ) = 39916800
factorial( 12 ) = 479001600
C:\dmd\MKOD_ex>
|