XML: Macros - Extracting Digits

From FSDeveloper Wiki
Revision as of 00:18, 4 May 2014 by Rpmc (talk | contribs)
Jump to: navigation, search

Extract Digits Macro

Quite frequently it is necessary to extract the nth digit of a number for any number of reasons. This XML Macro is very handy for the purpose, as it is "universal" and does not care what the number is...

 <Macro Name="ExtDigit"> 
  @1 sp0 
  @3 0 >  
  if{ l0 10 @3 pow * sp0 } 
  l0 int 10 @2 pow % 10 @2 1 - 0 max pow / int  
 </Macro>

@ExtDigit((ALGVar),nDigit,nDecimals)


Where: (ALGVar) is the A,L or G var from where to extract the digit nDigit is the position of the digit to extract, starting from the right. nDecimals is the number of decimals to be included in the calcs.


For instance, for a value of 123.456789999999

@ExtDigit(LVar,1,0) means I want to extract the right most, discarding the decimals. It returns 3 
@ExtDigit(LVar,2,0) returns 2 ; 
@ExtDigit(LVar,3,0) returns 1 and 
@ExtDigit(LVar,4,0) and up returns 0 

using decimals:

@ExtDigit(LVar,1,2) returns 5  
@ExtDigit(LVar,2,2) returns 4  
@ExtDigit(LVar,3,2) returns 3  
@ExtDigit(LVar,4,2) returns 2  


Rotating Drum Example

To simulate a Rotating Drum number using a value of three integer digits (ie (L:Var, number) = 135) where the preceding number starts to rotate at 90% of the number to its right:

-for the first rightmost integer digit (5) = (L:Var, number) 1 % @ExtDigit((L:Var, number),1,0) +
-for the second rightmost digit (3) = (L:Var, number) 10 % s1 9 >= l1 9 - * @ExtDigit((L:Var, number),2,0) +
-for the third rightmost digit (1) = (L:Var, number) 100 % s1 99 >= l1 99 - * @ExtDigit((L:Var, number),3,0) +

It is very simple to change the time the preceding digit starts to rotate by changing the 9 and 99 values. For example, if you want to start at 80 % of cycle instead of 90 % just use

-for the second rightmost digit (3) = (L:Var, number) 10 % s1 8 >= l1 8 - 2 / * @ExtDigit((L:Var, number),2,0) +

and

-for the third rightmost digit (1) = (L:Var, number) 100 % s1 98 >= l1 98 - 2 / * @ExtDigit((L:Var, number),3,0) +

and so on.

NOTES:

1. @1 sp0 - this s(tores) the value of @1 in register 0 (zero) and p(ops) the number from the stack
2. l0 - this is a lower case L, and not a 1 (one)! This means l(oad) the value from the 0 (zero) register
3. @1 @2 @3 - this is how an @Macro passes parameters. The @1 is the first parameter passed from it, etc. Used like so:
    @Macro1(Param1,Param2,Param3)
    @1 passes Param1 
    @2 passes Param2
    @3 passes Param3