Search code examples
ibm-midrangebit-shiftrpgle

Bit shifting in RPGLE


I languages such as Java or C, we got to use bit shifting operands. Example:

myValue <<= 1

How can I accomplish the same thing in RPGLE? (if possible)


Solution

  • For <<, divide by 2, 4, 8 etc. For >>, multiply by 2, 4, 8 etc.

    To get the 2, 4, 8 etc from n = 1, 2, 3, use %inth(2 ** n).

    For division, use %div rather than the / operator, to avoid getting decimal places.

    C: 
       n = 5;
       i <<= n;
       i >>= n;
    
    RPG:
       n = 5;
       i *= %inth(2 ** n);
       i = %div(i : %inth(2 ** n));
     or
       i = shift_left (i : n);
       i = shift_right (i : n);
    
    dcl-proc shift_left;                             
       dcl-pi *n int(20);                            
          value int(20) value;                       
          shift int(20) value;                       
       end-pi;                                       
       return value * %inth(2 ** shift);             
    end-proc;                                        
    dcl-proc shift_right;                            
       dcl-pi *n int(20);                            
          value int(20) value;                       
          shift int(20) value;                       
       end-pi;                                       
       return %div(value : %inth(2 ** shift));       
    end-proc;