IBM Support

How to display in hexadecimal using COBOL

Troubleshooting


Problem

Convert a hex number such as CA84 or a binary number defined as USAGE IS COMPUTATIONAL into a printable hex string in EBCDIC.

Cause

COBOL has no converter. A program is needed.

Resolving The Problem

This is just an illustration. It's not guaranteed.
IDENTIFICATION DIVISION.                      
PROGRAM-ID. HEXPRINT.
*REMARKS.  CONVERT FROM BINARY TO PRINTABLE HEX.
ENVIRONMENT DIVISION.                          
DATA DIVISION.                                
WORKING-STORAGE SECTION.
* HEXVAL (output) must be twice the size of HEXNUM (input).
* For example if you have 20 bytes of garbage but
* want to display it in hex, change the picture
* of HEXNUM to X(20), of HEXVAL to X(40), then
* move the garbage to HEXNUM. Ignore DECNUM.
01  HEXNUM   PIC X(4) VALUE X"0000CA84".      
01  DECNUM   REDEFINES HEXNUM PIC S9(8) COMP.  
01  HEXVAL   PIC X(8).                          
01  HEXSTR   PIC X(16) VALUE "0123456789ABCDEF".
01  DEC      PIC S9(4) COMP.                    
01  FILLER   REDEFINES DEC.                    
    02  FILLER PIC X.                          
    02  DECBYTE PIC X.                          
01  I   PIC S9(8) COMP.                        
01  J   PIC S9(8) COMP.                        
01  Q   PIC S9(8) COMP.                        
01  R   PIC S9(8) COMP.                        
01  J1  PIC S9(8) COMP.                        
01  Q1  PIC S9(8) COMP.                        
01  R1  PIC S9(8) COMP.                        
PROCEDURE DIVISION.                              
TEST-IT.        
    DISPLAY "Hex        " HEXNUM.              
    DISPLAY "Dec        " DECNUM.              
    PERFORM CONVERT                            
    DISPLAY "Printable  " HEXVAL.
    GOBACK.                                  
CONVERT.                                      
    PERFORM VARYING I FROM 1 BY 1 UNTIL I > LENGTH OF HEXNUM
      COMPUTE J = 2 * I - 1                  
      MOVE HEXNUM(I:1) TO DECBYTE            
      DIVIDE DEC BY 16 GIVING Q REMAINDER R  
      COMPUTE J1 = J + 1                      
      COMPUTE Q1 = Q + 1                      
      COMPUTE R1 = R + 1                      
      MOVE HEXSTR(Q1:1) TO HEXVAL(J:1)        
      MOVE HEXSTR(R1:1) TO HEXVAL(J1:1)      
    END-PERFORM.
_________Results_______
Hex           d       ----  This is all you get DISPLAY HEXNUM
Dec        00051844   ----  Decimal equivalent of X'CA84'
Printable  0000CA84   ----  After conversion.

[{"Product":{"code":"SS6SG3","label":"Enterprise COBOL for z\/OS"},"Business Unit":{"code":"BU011","label":"Systems - zSystems"},"Component":"Runtime","Platform":[{"code":"PF035","label":"z\/OS"}],"Version":"3.4;4.1;4.2;5.1;5.2","Edition":""}]

Document Information

Modified date:
08 August 2018

UID

swg21177358