Search code examples
hexcharacterbitwise-operatorsibm-midrangerpg

Convert HEX to characters using bitwise operations


Say I've got this value xxx in hex 007800780078
How can I convert back the hex value to characters using bitwise operations? Can I?


Solution

  • I suppose you could do it using "bitwise" operations, but it'd probably be a horrendous mess of code as well as being totally unnecessary since ILE RPG can do it easily using appropriate built-in functions.

    First is that you don't exactly have what's usually thought of as a "hex" value. That is, you're showing a hexadecimal representation of a value; but basic "hex" conversion will not give a useful result. What you're showing seems to be a UCS-2 value for "xxx".

    Here's a trivial example that shows a conversion of that hexadecimal string into a standard character value:

     d                 ds
     d charField                      6    inz( x'007800780078' )
     d UCSField1                      3c   overlay( charField )
    
     d TargetField     s              6
     d Length          s             10i 0
    
      /free
        Length = %len( %trim( UCSField1 ));
        TargetField = %trim( %char( UCSField1 ));
    
        *inlr = *on;
        return;
      /end-free
    

    The code has a DS that includes two sub-fields. The first is a simple character field that declares six bytes of memory initialized to x'007800780078'. The second sub-field is declared as data type 'C' to indicate UCS-2, and it overlays the first sub-field. Because it's UCS-2, its size is given as "3" to allow for three characters. (Each character is 16-bits wide.)

    The executable statements don't do much, just enough to let you test the converted values. Using debug, you should see that Length comes out to be (3) and TargetField becomes 'xxx'.

    The %CHAR() built-in function can be used to convert from UCS-2 to the character encoding used by the program. To go in the opposite direction, use the %UCS2() built-in function.