Built in functions

Here is a complete list of RPGLE built in functions, with some comments and examples on on the more useful or  interesting ones.  Most of this stuff was liberally lifted from the IBM WebSphere(R) Development Studio ILE RPG Reference manual. 

%ABS Absolute Value of Expression 

%ABS(numeric expression)

%ABS returns the absolute value of the numeric expression specified as the parameter. If the value of the numeric expression is non-negative, the value is returned unchanged. If the value is negative, the value returned is the value of the expression but with the negative sign removed.

%ADDR - Get Address of Variable

%ADDR(variable)
%ADDR(variable(index))
%ADDR(variable(expression))

%ADDR returns a value of type basing pointer. The value is the address of the specified variable. It may only be compared with and assigned to items of type basing pointer.

%ALLOC - Allocate Storage

%ALLOC(num)

%ALLOC returns a pointer to newly allocated heap storage of the length specified. The newly allocated storage is uninitialized.


%BITAND - Bitwise AND Operation

%BITAND(expr:expr{:expr...})

%BITAND returns the bit-wise ANDing of the bits of all the arguments. That is, the result bit is ON when all of the corresponding bits in the arguments are ON, and OFF otherwise.


%BITNOT (Invert Bits)

%BITNOT(expr)

%BITNOT returns the bit-wise inverse of the bits of the argument. That is, the result bit is ON when the corresponding bit in the argument is OFF, and OFF otherwise.


%BITOR - Bitwise OR Operation

%BITOR(expr:expr{:expr...})

%BITOR returns the bit-wise ORing of the bits of all the arguments. That is, the result bit is ON when any of the corresponding bits in the arguments are ON, and OFF otherwise.

%BITXOR - Bitwise Exclusive-OR Operation

%BITXOR(expr:expr)

%BITXOR returns the bit-wise exclusive ORing of the bits of the two arguments. That is, the result bit is ON when just one of the corresponding bits in the arguments are ON, and OFF otherwise.



%CHAR - Convert to Character Data

%CHAR(expression{:format})

%CHAR converts the value of the expression from graphic, UCS-2, numeric, date, time or timestamp data to type character. The converted value remains unchanged, but is returned in a format that is compatible with character data.

  // to assign a number to a character field 
  // the old way results in Character1 having the value of '0001234567'
d*------------------------------------------------------------ 
d Number1         S             10  2 inz(12345.67)    
d Character1      S             10                      
c*------------------------------------------------------------ 
c                   Move      Number1       Character1       
c*------------------------------------------------------------ 

 

  // Note that with the built-in function %char the value returned is 
  // a bit different from the result obtained using the MOVE command. 
  // The results of a %char function are left justified and left 
  // zeros are suppressed. 
  // using %char:  
  //     Character1 will have the value of '12345.67  '     
  //     Character2 will have the value of '-12345.67 '   
c*------------------------------------------------------------ 
d Number1         S             10  2 inz(12345.67)         
d Number2         S             10S 2 inz(-12345.67)        
d Character1      S             10                           
d Character2      S             10                           
 /Free                                                       
                               Character1 = %char(Number1) ; 
                               Character2 = %char(Number2) ; 
 /End-free                                                   
c*------------------------------------------------------------ 

%CHECK - Check Characters

%CHECK(comparator : base {: start})

%CHECK returns the first position of the string base that contains a character that does not appear in string comparator. If all of the characters in base also appear in comparator, the function returns 0.

// find the first character that is not a '*'
// in this example  position would be equal 11 
d*------------------------------------------------------------ 
d string          S             15    inz('**********12345') 
d findme          S              1    inz('*')               
d pos             S             10i 0                        
 /Free                                                       
                  pos = %check (findme : string);            
 /End-free                                                   


%CHECKR (Check Reverse)

%CHECKR(comparator : base {: start})

%CHECKR returns the last position of the string base that contains a character that does not appear in string comparator. If all of the characters in base also appear in comparator, the function returns 0. 

The check begins at the starting position and continues to the left until a character that is not contained in the comparator string is found. The starting position defaults to the end of the string. 

// going from right to left, the first character that
// is not a '*' is in the sixth position from the left,
// so pos is equal to 6
*------------------------------------------------------------ 
d string          S             15    inz('ABCBDF*********') 
d findme          S              1    inz('*')               
d pos             S             10i 0                        
d*---------------------------------------------------------- 
 /Free                                                       
                  pos = %checkr (findme : string);           
 /End-free                                                   


%DATE (Convert to Date)

%DATE{(expression{:date-format})}

%DATE converts the value of the expression from character, numeric, or timestamp data to type date. The converted value remains unchanged, but is returned as a date. 

The first parameter is the value to be converted. If you do not specify a value, %DATE returns the current system date. 

The second parameter is the date format for character or numeric input. Regardless of the input format, the output is returned in *ISO format. 

d today           S               D
d date1           S               D
d date2           S               D
d string          S             10    inz('2002-12-01')
d numeric         S              8  0 inz(20021130)
d*----------------------------------------------------------
 /free
    // set today to today's date. 
    // These two statements have identical results.
    today=  %date;                
    today=  %date(*date);         

    // set date based on 10 character date string '2002-12-01'
    date1=  %date(string)     ;

    // set date based on numeric value 20021130
    date2=  %date(numeric)    ;

    *inlr   = *on             ;			
 /end-free


%DAYS (Number of Days)

%DAYS(number)

%DAYS converts a number into a duration that can be added to a date or timestamp value. 

%DAYS can only be the right-hand value in an addition or subtraction operation. The left-hand value must be a date or timestamp. The result is a date or timestamp value with the appropriate number of days added or subtracted. For a date, the resulting value is in *ISO format. 

%DEC - Convert to Packed Decimal Format

%DEC(numeric or character expression{:precision:decimal places})

%DEC converts the value of the numeric or character expression to decimal (packed) format with precision digits and decimal places decimal positions. The precision and decimal places must be numeric literals, named constants that represent numeric literals, or built-in functions with a numeric value known at compile-time. 

Parameters precision and decimal places may be omitted if the type of expression is neither float nor character. If these parameters are omitted, the precision and decimal places are taken from the attributes of numeric expression. 

If the parameter is a character expression, the following rules apply: 

o The sign is optional. It can be '+' or '-'. It can precede or follow the numeric data.
o The decimal point is optional. It can be either a period or a comma.
o Blanks are allowed anywhere in the data. For example, ' + 3 ' is a valid parameter.
o The second and third parameters are required.
o Floating point data, for example '1.2E6', is not allowed.
o If invalid numeric data is found, an exception occurs with status code 105.

here is a common old way of moving character and signed to packed:

*------------------------------------------------------------
d character1      S              5    inz('12345')
d character2      S              5    inz('1 3 5')
d character3      S              5    inz('1234w')
d signed          S              5S 0 inz(12345)
d packed          S              5  0
d*----------------------------------------------------------
c
 *     // old way of assigning characters '12345' to a packed numeric
c                   MOVE      character1    packed

 *     // this works, but gives you a value of 10305
 *     // maybe not what you wanted, should have done a TESTN first!
c                   MOVE      character2    packed

 *     // this works, but gives you a value of 12346
 *     // This is probably not at all what was expected
c                   MOVE      character3    packed

Here is how to do the same with Build-in-Functions  and RPG /free

*------------------------------------------------------------
d character1      S              5    inz('12345')
d character2      S              5    inz('1 3 5')
d character3      S              5    inz('1234w')
d signed          S              5S 0 inz(12345)
d packed          S              5  0
d*----------------------------------------------------------
/free
      // assign  characters '12345' to a packed numeric
      packed = %dec(character1:5:0) ;    // packed = 12345

      // note in this example the blanks are ignored!
      packed = %dec(character2:5:0) ;    // packed = 135

      // assign signed to a packed numeric
      packed = %dec(signed)        ;

      // nice try - an alpha here will crash the program
      packed = %dec(character3:5:0) ;    // *CRASH*
      *inlr  = *on                 ;
 
/end-free

 

%DECH  Convert to Packed Decimal Format with Half Adjust

%DECH(numeric or character expression :precision:decimal places )

%DECH is the same as %DEC except that if the expression is a decimal or float value, half adjust is applied to the value of the expression when converting to the desired precision. No message is issued if half adjust cannot be performed.. 

Unlike, %DEC, all three parameters are required. 

D signed          s              7s 5 inz (73.73551)    
D packed1         s              7p 5                   
D packed2         s              7p 5                   
 /FREE                                                  
       packed1 = %dec(signed:5:2);  // result is 73.73000                    
       packed2 = %dech(signed:5:2); // result is 73.74000                     
       *inLR = *ON   ;                                  
 /END-FREE                                              


%DECPOS (Get Number of Decimal Positions)

%DECPOS(numeric expression)

%DECPOS returns the number of decimal positions of the numeric variable or expression. The value returned is a constant, and
so may participate in constant folding. 

The numeric expression must not be a float variable or expression. 
%DECPOS(numeric expression)

%DECPOS returns the number of decimal positions of the numeric variable or expression. The value returned is a constant, and
so may participate in constant folding. 

The numeric expression must not be a float variable or expression. 

%DECH  Convert to Packed Decimal Format with Half Adjust

%DECH(numeric or character expression :precision:decimal places )

%DECH is the same as %DEC except that if the expression is a decimal or float value, half adjust is applied to the value of the expression when converting to the desired precision. No message is issued if half adjust cannot be performed.. 

Unlike, %DEC, all three parameters are required. 

 D packed1         s              7p 3 inz (8236.567)
 D signed1         s              9s 5 inz (23.73442)
 D result1         s              5i 0
 D result2         s              5i 0
  /FREE
     result1 = %decpos (packed1); //  "result1" is  3 
     result2 = %decpos (signed1); //  "result2" is  5  
     *inLR = *ON;
  /END-FREE
 


%DIFF (Difference Between Two Date, Time, or Timestamp Values)

%DIFF(op1:op2:*MSECONDS|*SECONDS|*MINUTES|*HOURS|*DAYS|*MONTHS|*YEARS)
%DIFF(op1:op2:*MS|*S|*MN|*H|*D|*M|*Y)

%DIFF produces the difference (duration) between two date or time values. The first and second parameters must have the same, or compatible types. The following combinations are possible: 

Date and date 
Time and time 
Timestamp and timestamp 
Date and timestamp (only the date portion of the timestamp is considered) 
Time and timestamp (only the time portion of the timestamp is considered). 

The third parameter specifies the unit. The following units are valid: 

For two dates or a date and a timestamp: *DAYS, *MONTHS, and *YEARS 
For two times or a time and a timestamp: *SECONDS, *MINUTES, and *HOURS 
For two timestamps: *MSECONDS, *SECONDS, *MINUTES, *HOURS, *DAYS, *MONTHS, and *YEARS 

The result is rounded down, with any remainder discarded. For example, 61 minutes is equal to 1 hour, and 59 minutes is equal to 0 hours. 

The value returned by the function is compatible with both type numeric and type duration. You can add the result to a number (type numeric) or a date, time, or timestamp (type duration). 

 D DaysLate        s              7  0
 D DueDate         s               d
 D PaidDate        s               d
  /FREE
     // Determine hoe many days late the payment was made
     DueDate  = d'2003-01-01';
     PaidDate = d'2003-03-12';
     DaysLate = %DIFF(PaidDate:DueDate: *Days);
     *inLR = *ON ;
  /END-FREE


%DIV (Return Integer Portion of Quotient)

%DIV(n:m)

%DIV returns the integer portion of the quotient that results from dividing operands n by m. The two operands must be numeric values with zero decimal positions. If either operand is a packed, zoned, or binary numeric value, the result is packed numeric. If either operand is an integer numeric value, the result is integer. Otherwise, the result is unsigned numeric. Float numeric operands are not allowed. (See also %REM (Return Integer Remainder).) 

If the operands are constants that can fit in 8-byte integer or unsigned fields, constant folding is applied to the built-in function. In this case, the %DIV built-in function can be coded in the definition specifications. 

D NUMERATOR       S             10I 0 INZ(123)
D DENOMINATOR     S             10I 0 INZ(27)
D DIV             S             10I 0
D REM             S             10I 0
D E               S             10I 0
 /FREE
   DIV = %DIV(NUMERATOR:DENOMINATOR) ; // DIV is now 4
   DIV = NUMERATOR/DENOMINATOR       ; // '/' does the same thing
   REM = %REM(NUMERATOR:DENOMINATOR) ; // REM is now 15
   E   = DIV*DENOMINATOR  + REM      ; // E is now 123
   EVAL DIV = NUMERATOR/DENOMINATOR  ;
   *INLR = *ON;
 /END-FREE
        


%EDITC (Edit Value Using an Editcode)

...


%EDITFLT (Convert to Float External Representation)

%EDITFLT converts the value of the numeric expression to the character external display representation of float. The result is either 14 or 23 characters. If the argument is a 4-byte float field, the result is 14 characters. Otherwise, it is 23 characters.

If specified as a parameter to a definition specification keyword, the parameter must be a numeric literal, float literal, or numeric valued constant name or built-in function. When specified in an expression, constant folding is applied if the numeric expression has a constant value.

If the operands are constants that can fit in 8-byte integer or unsigned fields, constant folding is applied to the built-in function. In this case, the %DIV built-in function can be coded in the definition specifications. 

d f8              s              8f   inz (50000)                                
d string          s             40a   varying                                    
d                                                                                
 /free                                                                           
     // Value of "string" is 'Float value is +4.000000000000000E+004. '          
     string = 'Float value is ' + %editflt (f8 - 1E4) + '.'              ;       
     // Value of "string" is now 'Float value is +1.000000000000000E+004. '      
     string = 'Float value is ' + %editflt (f8 - 4E4) + '.'              ;       
     Eval *INlr = *ON                                                    ;       
 /end-free                                                                       


%EDITW  - Edit Value Using an Editword
 

%EDITW(numeric : editword)
This function returns a character result representing the numeric value edited according
to the edit word. The rules for the numeric value and edit word are identical to those for editing numeric values in output specifications.

Float expressions are not allowed in the first parameter. Use %DEC to convert a float to an editable format.

The edit word must be a character constant. This function was added with V3R7.  Here is more background on the Edit code and edit word.

D* note the example from the manual doesn't work properly 
D amount S 50A 
D salary S 9P 2 
D editwd C '$ , , **Dollars& &Cents' 
 /free 
    // output: 'The annual salary is $*******2451*Dollars 53 Cents' 
    eval salary = 2451.53 ; 
    amount = 'The annual salary is ' + %editw(salary : editwd) ; 

    // you can even to multiplication in there! 
    // output: 'The annual salary is $*******4903*Dollars 06 Cents' 
    eval salary = 2451.53 ; 
    amount = 'The annual salary is ' + %editw(salary * 2 : editwd) ; 
    // look: easy zero supression! 
    // output: 'The annual salary is $************Dollars 00 Cents' 
    eval salary = 0 ; 
    amount = 'The annual salary is ' + %editw(salary : editwd) ;   

   eval *inlr = *on ; 
 /end-free 

%ELEM - Get Number of Elements

%ELEM(table_name)
%ELEM(array_name)
%ELEM(multiple_occurrence_data_structure_name)

%ELEM returns the number of elements in the specified array, table, or multiple-occurrence data structure. The value returned is in unsigned integer format (type U). It may be specified anywhere a numeric constant is allowed in the definition specification or in an expression in the extended factor 2 field.

The parameter must be the name of an array, table, or multiple occurrence data structure.

 

  
D arr1d           S             20    DIM(10)                               
D table           S             10    DIM(20) ctdata                        
D mds             DS            20    occurs(30)                            
D num             S              5p 0                                       
                                                                            
 * like_array will be defined with a dimension of 10.                       
 * array_dims will be defined with a value of 10.                           
D like_array      S                   like(arr1d) dim(%elem(arr1d))         
D array_dims      C                   const (%elem (arr1d))                 
  /free 
   num = %elem (arr1d); // num is now 10 ; 
   num = %elem (table); // num is now 20 ; 
   num = %elem (mds); // num is now 30 ; 
   Eval *inlr = *on ; 
 /end-free 


%EOF -  Return End or Beginning of File Condition
%EQUAL (Return Exact Match Condition)
%ERROR (Return Error Condition)
%FIELDS (Fields to update)
%FLOAT (Convert to Floating Format)
%FOUND (Return Found Condition)
%GRAPH (Convert to Graphic Value)
%HOURS (Number of Hours)
%INT (Convert to Integer Format)
%INTH (Convert to Integer Format with Half Adjust)
%KDS (Search Arguments in Data Structure)
%LEN (Get or Set Length)
%LEN Used for its Value
%LEN Used to Set the Length of Variable-Length Fields
%LOOKUPxx (Look Up an Array Element)
%MINUTES (Number of Minutes)
%MONTHS (Number of Months)
%MSECONDS (Number of Microseconds)
%NULLIND (Query or Set Null Indicator)
%OCCUR (Set/Get Occurrence of a Data Structure)
%OPEN (Return File Open Condition)
%PADDR (Get Procedure Address)
%PADDR Used with a Prototype
%PARMS (Return Number of Parameters)
%REALLOC (Reallocate Storage)
%REM (Return Integer Remainder)
%REPLACE (Replace Character String)
%SCAN (Scan for Characters)
%SECONDS (Number of Seconds)
%SHTDN (Shut Down)
%SIZE (Get Size in Bytes)
%SQRT (Square Root of Expression)
%STATUS (Return File or Program Status)
%STR (Get or Store Null-Terminated String)
%STR Used to Get Null-Terminated String
%STR Used to Store Null-Terminated String
%SUBDT (Extract a Portion of a Date, Time, or Timestamp)
%SUBST (Get Substring)
%SUBST Used for its Value
%SUBST Used as the Result of an Assignment
%THIS (Return Class Instance for Native Method)
%TIME (Convert to Time)
%TIMESTAMP (Convert to Timestamp)
%TLOOKUPxx (Look Up a Table Element)
%TRIM (Trim Blanks at Edges)
%TRIML (Trim Leading Blanks)
%TRIMR (Trim Trailing Blanks)
%UCS2 (Convert to UCS-2 Value)
%UNS (Convert to Unsigned Format)
%UNSH (Convert to Unsigned Format with Half Adjust)
%XFOOT (Sum Array Expression Elements)
%XLATE (Translate)
%YEARS (Number of Years)

more to come ...


 

Link to the AS/400 Learnin' Project

Hosted by www.Geocities.ws

1