1   package org.djutils.decoderdumper;
2   
3   import java.io.IOException;
4   
5   
6   
7   
8   
9   
10  
11  
12  
13  
14  public class HexDecoder implements Decoder
15  {
16      
17      private final String prototypeLine;
18  
19      
20      private int fieldsPerLine;
21  
22      
23      private final int extraSpaceAfterEvery;
24  
25      
26  
27  
28  
29  
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      
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  }