News:

PlayBASIC2DLL V0.99 Revision I Commercial Edition released! - Convert PlayBASIC programs to super fast Machine Code. 

Main Menu

Learn To Code: 16bit Binary Multiply and Division operations

Started by kevin, March 19, 2022, 08:32:48 PM

Previous topic - Next topic

kevin

   Learn To Code:  16bit Binary Multiply and Division operations

   Ever wonder how your computers performs Multiply or even Division in a fixed time ?    

   

     OPerators Used:  + Addition  - Subtraction  << Shit Left/Up  >> Shift Right/Down  and ^ power


PlayBASIC Code: [Select]
; PROJECT : 16bit Multiply and Divide Functions
; AUTHOR : Kevin Picone - PlayBASIC Tutor
; CREATED : 20/03/2022
; EDITED : 20/03/2022
; ---------------------------------------------------------------------

// Run Code in DEBUG MODE (f7 from IDE)


MaxTests=100

Test_Mults(MaxTests)

Test_Division(MaxTests)

Sync
waitkey



Function Test_Mults(MaxTests)

s$=make$("-",100)
#print s$
#print "Multiply Test"+make$("-",60)
#print s$
a=100
for lp= 1 to MaxTests
a=rnd($ffff)
b=rnd($ffff)

result1=Mult(a,b)
result2=a*b

Status=Result1<>Result2
Failed+=Status
#print "Mult:("+str$(a)+","+str$(b)+")="+str$(Result1)+" A*B="+str$(result2)+" Status="+str$(Status)
next
#print ""
#print "Result="+Str$(Failed)+" Fails"
#print s$
#print ""
#print ""

Endfunction




Function Test_Division(MaxTests)

s$=make$("-",100)
#print s$
#print "Division Test"+make$("-",60)
#print s$
a=100
for lp= 1 to MaxTests
a=rnd($ffff)
b=rnd($ffff)
swapiflower a,b

result1,Remainder1 =Div(a,b)
result2 =a/b
Remainder2 = a-(B*result2)
Status=Result1<>Result2
Failed+=Status
#print "Div:("+str$(a)+","+str$(b)+")="+str$(Result1)+" Remainder:"+str$(Remainder1)+" A/B="+str$(result2)+" Remainder:"+str$(Remainder2)+" Status="+str$(Status)
next
#print ""
#print "Result="+Str$(Failed)+" Fails"
#print s$
#print ""
#print ""

Endfunction



/* -------------------------------------------------------------
------------>> Unsigned Integer 16bit Multiply <<------------
-------------------------------------------------------------

This function performs a fixed time unsigned 16bit multiply
between a pair of 16 bit integers.

------------------------------------------------------------- */



Function Mult(A,B)

if B
For lp =0 to 15
if B and 1
Result += A << lp
endif
B=B >> 1
next
endif

EndFunction Result


/* -------------------------------------------------------------
------------>> Unsigned Integer 16bit Divider <<------------
-------------------------------------------------------------

This function performs a fixed time unsigned 16bit division
with remainder between a pair of 16bit integers

------------------------------------------------------------- */



Function Div(A,B)
remainder=A
if B
For lp =15 to 0 step -1
if (B<<lp)<=A
A-=(B<<lp)
Result+=2 ^ lp
endif
next
remainder=A
endif

EndFunction Result,Remainder