View Javadoc
1   package org.djutils.decoderdumper;
2   
3   import java.io.IOException;
4   
5   /**
6    * Dump bytes as hexadecimal numbers
7    * <p>
8    * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
9    * BSD-style license. See <a href="https://djutils.org/docs/current/djutils/licenses.html">DJUTILS License</a>.
10   * </p>
11   * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a>
12   * @author <a href="https://www.tudelft.nl/staff/p.knoppers/">Peter Knoppers</a>
13   */
14  public class HexDecoder implements Decoder
15  {
16      /** Prototype output line. */
17      private final String prototypeLine;
18  
19      /** Number of fields on an output line. */
20      private int fieldsPerLine;
21  
22      /** Insert one extra space every N fields. */
23      private final int extraSpaceAfterEvery;
24  
25      /**
26       * Construct a new HexDecoder.
27       * @param fieldsPerLine int; maximum number of hex values on one output line this.extraSpaceAfterEvery =
28       *            extraSpaceAfterEvery;
29       * @param extraSpaceAfterEvery int; insert an extra space after every N fields
30       */
31      public HexDecoder(final int fieldsPerLine, final int extraSpaceAfterEvery)
32      {
33          this.fieldsPerLine = fieldsPerLine;
34          this.extraSpaceAfterEvery = extraSpaceAfterEvery > 0 ? extraSpaceAfterEvery : Integer.MAX_VALUE;
35          String format =
36                  String.format("%%%ds", fieldsPerLine * 2 + fieldsPerLine - 1 + (fieldsPerLine - 1) / this.extraSpaceAfterEvery);
37          this.prototypeLine = String.format(format, "");
38      }
39  
40      /** String builder for current output line. */
41      private StringBuilder buffer = new StringBuilder();
42  
43      @Override
44      public String getResult()
45      {
46          String result = this.buffer.toString();
47          this.buffer.setLength(0);
48          return result;
49      }
50  
51      @Override
52      public int getMaximumWidth()
53      {
54          return this.prototypeLine.length();
55      }
56  
57      @Override
58      public boolean append(final int address, final byte theByte) throws IOException
59      {
60          if (this.buffer.length() == 0)
61          {
62              this.buffer.append(this.prototypeLine);
63          }
64          int lineByte = address % this.fieldsPerLine;
65          int index = lineByte * 3 + lineByte / this.extraSpaceAfterEvery;
66          this.buffer.replace(index, index + 2, String.format("%02x", theByte));
67          return lineByte == this.fieldsPerLine - 1;
68      }
69  
70      @Override
71      public boolean ignoreForIdenticalOutputCheck()
72      {
73          return false;
74      }
75  
76      @Override
77      public String toString()
78      {
79          return "HexDecoder [buffer=" + this.buffer + "]";
80      }
81  
82  }