1 package org.djutils.decoderdumper;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5
6 /**
7 * Dump data in hexadecimal format and (insofar possible) as characters.
8 * <p>
9 * Copyright (c) 2013-2019 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
10 * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
11 * <p>
12 * @version $Revision$, $LastChangedDate$, by $Author$, initial version Jan 3, 2019 <br>
13 * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
14 * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
15 * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
16 */
17 public class HexDumper extends Dumper<HexDumper>
18 {
19
20 /**
21 * Construct a new HexDumper.
22 * @param addressOffset int; address of the first byte that will be appended
23 */
24 public HexDumper(final int addressOffset)
25 {
26 super(addressOffset);
27 addDecoder(new HexAddressDecoder(16));
28 addDecoder(new FixedString(": "));
29 addDecoder(new HexDecoder(16, 8));
30 addDecoder(new FixedString(" "));
31 addDecoder(new CharDecoder(16, 8));
32 addDecoder(new FixedString("\n"));
33 }
34
35 /**
36 * Construct a new HexDumper.
37 */
38 public HexDumper()
39 {
40 this(0);
41 }
42
43 /**
44 * Create a HexDumper object; use it to dump an array of bytes and return the dump as a String.
45 * @param addressOffset int; address of the first byte
46 * @param bytes byte[]; the bytes to hex-dump
47 * @return String; the hexadecimal and character dump of the <code>bytes</code>
48 */
49 public static String hexDumper(final int addressOffset, final byte[] bytes)
50 {
51 ByteArrayOutputStream baos = new ByteArrayOutputStream();
52 try
53 {
54 new HexDumper(addressOffset).setOutputStream(baos).append(bytes).flush();
55 }
56 catch (IOException exception)
57 {
58 // Cannot happen because ByteOutputStream.write(byte[]) cannot fail
59 }
60 return baos.toString();
61 }
62
63 /**
64 * Create a HexDumper object with addressOffset 0; use it to dump an array of bytes and return the dump as a String.
65 * @param bytes byte[]; the bytes to hex-dump
66 * @return String; the hexadecimal and character dump of the <code>bytes</code>
67 */
68 public static String hexDumper(final byte[] bytes)
69 {
70 return hexDumper(0, bytes);
71 }
72
73 /** {@inheritDoc} */
74 @Override
75 public String toString()
76 {
77 return "HexDumper [super=" + super.toString() + "]";
78 }
79
80 }