title: How to decode comp 3 packed fields in an ascii file using java?
body: <p>I have a huge mainframe file extracted from a legacy system. The file is encoded in ascii format. I want to convert that to comp3. Is there any algorithm available in java to do that? Also I need assistance on how to unpack the comp3 fields. I tried a java code to unpack comp3 but I found improper result</p>
  
  <p>Please refer the code to unpack comp3 fields</p>
  
  <pre><code>import java.math.BigInteger;
  import java.nio.file.Files;
  import java.nio.file.Path;
  import java.nio.file.Paths;
  
  /**
   * Converts between integer and an array of bytes in IBM mainframe packed
   * decimal format. The number of bytes required to store an integer is (digits +
   * 1) / 2. For example, a 7 digit number can be stored in 4 bytes. Each pair of
   * digits is packed into the two nibbles of one byte. The last nibble contains
   * the sign, 0F for positive and 0C for negative. For example 7654321 becomes
   * 0x76 0x54 0x32 0x1F.
   **/ 
  
  
  public class PackedDecimalToComp {
  
      public static void main(String[] args) {
  
          try {
              // test.unpackData(" 0x12345s");
              Path path = Paths.get("C:\\Users\\AV00499269\\Desktop\\Comp3 data file\\Comp3Test.txt");
              byte[] data = Files.readAllBytes(path);
              PackedDecimalToComp test = new PackedDecimalToComp();
              test.unpackData(data);
          } catch (Exception ex) {
              System.out.println("Exception is :" + ex.getMessage());
          }    
      }
  
      private static String unpackData(byte[] packedData) {
          String unpackedData = "";
  
          final int negativeSign = 13;
          for (int currentCharIndex = 0; currentCharIndex &lt; packedData.length; currentCharIndex++) {
              byte firstDigit = (byte) ((packedData[currentCharIndex] &gt;&gt;&gt; 4) &amp; 0x0F);
              byte secondDigit = (byte) (packedData[currentCharIndex] &amp; 0x0F);
              unpackedData += String.valueOf(firstDigit);
              if (currentCharIndex == (packedData.length - 1)) {
                  if (secondDigit == negativeSign) {
                      unpackedData = "-" + unpackedData;
                  }
              } else {
                  unpackedData += String.valueOf(secondDigit);
              }
          }
          System.out.println("Unpackeddata is :" + unpackedData);
  
          return unpackedData;
      }    
  }
  </code></pre>