Search code examples
c#javacobolpacked-decimal

How to convert unpacked decimal back to COMP-3?


I had asked a question about converting COMP fields, for which I did not get any answer.

I hope stack-overflow can help me on this question.

I succeeded in converting COMP-3 to decimal. I need your help in converting the unpacked decimal back to COMP-3, in any high level programming language, but preferably in Java or c#.net.


Solution

  • In packed decimal -123 is represented as X'123d' (the last nyble c,d or f being the sign). One of the simplest ways to handle packed decimal is to simply convert the bytes to a hex string (or vice versa as required) then use normal string manipulation. This may not be the most efficient but it is easy to implement.

    So to convert a Integer (value) to packed decimal is roughly (note: I have not tested the code)

    String sign = "c";
    if (value < 0) {
        sign = "d";
        value = -1 * value;
    }
    String val = value + "d"
    
    byte[] comp3Bytes = new BigInteger(val, 16).toByteArray();
    

    Following are some example code for converting to/from comp3 To retrieve a packed decimal from an array of bytes see method getMainframePackedDecimal in http://record-editor.svn.sourceforge.net/viewvc/record-editor/Source/JRecord/src/net/sf/JRecord/Common/Conversion.java?revision=3&view=markup

    and to set a packed decimal see setField in http://record-editor.svn.sourceforge.net/viewvc/record-editor/Source/JRecord/src/net/sf/JRecord/Types/TypePackedDecimal.java?revision=3&view=markup

    both routines take an array of bytes, a start position and either a length of a field position.

    There are other examples of doing this on the web (JRanch I think has code for doing the conversion as well), do a bit of googling.