1 package org.djutils.decoderdumper;
2
3 import java.io.IOException;
4
5
6
7
8
9
10
11
12
13
14
15
16 public class HexDecoder implements Decoder
17 {
18
19 private final String prototypeLine;
20
21
22 private int fieldsPerLine;
23
24
25 private final int extraSpaceAfterEvery;
26
27
28
29
30
31
32
33 public HexDecoder(final int fieldsPerLine, final int extraSpaceAfterEvery)
34 {
35 this.fieldsPerLine = fieldsPerLine;
36 this.extraSpaceAfterEvery = extraSpaceAfterEvery > 0 ? extraSpaceAfterEvery : Integer.MAX_VALUE;
37 String format =
38 String.format("%%%ds", fieldsPerLine * 2 + fieldsPerLine - 1 + (fieldsPerLine - 1) / this.extraSpaceAfterEvery);
39 this.prototypeLine = String.format(format, "");
40 }
41
42
43 private StringBuilder buffer = new StringBuilder();
44
45
46 @Override
47 public String getResult()
48 {
49 String result = this.buffer.toString();
50 this.buffer.setLength(0);
51 return result;
52 }
53
54
55 @Override
56 public int getMaximumWidth()
57 {
58 return this.prototypeLine.length();
59 }
60
61
62 @Override
63 public boolean append(final int address, final byte theByte) throws IOException
64 {
65 if (this.buffer.length() == 0)
66 {
67 this.buffer.append(this.prototypeLine);
68 }
69 int lineByte = address % this.fieldsPerLine;
70 int index = lineByte * 3 + lineByte / this.extraSpaceAfterEvery;
71 this.buffer.replace(index, index + 2, String.format("%02x", theByte));
72 return lineByte == this.fieldsPerLine - 1;
73 }
74
75
76 @Override
77 public boolean ignoreForIdenticalOutputCheck()
78 {
79 return false;
80 }
81
82
83 @Override
84 public String toString()
85 {
86 return "HexDecoder [buffer=" + this.buffer + "]";
87 }
88
89 }