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-2022 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br> 10 * BSD-style license. See <a href="https://djutils.org/docs/current/djutils/licenses.html">DJUTILS License</a>. 11 * <p> 12 * @version $Revision$, $LastChangedDate$, by $Author$, initial version Jan 3, 2019 <br> 13 * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a> 14 * @author <a href="https://www.tudelft.nl/staff/p.knoppers/">Peter Knoppers</a> 15 */ 16 public class HexDumper extends Dumper<HexDumper> 17 { 18 19 /** 20 * Construct a new HexDumper. 21 * @param addressOffset int; address of the first byte that will be appended 22 */ 23 public HexDumper(final int addressOffset) 24 { 25 super(addressOffset); 26 addDecoder(new HexAddressDecoder(16)); 27 addDecoder(new FixedString(": ")); 28 addDecoder(new HexDecoder(16, 8)); 29 addDecoder(new FixedString(" ")); 30 addDecoder(new CharDecoder(16, 8)); 31 addDecoder(new FixedString("\n")); 32 } 33 34 /** 35 * Construct a new HexDumper. 36 */ 37 public HexDumper() 38 { 39 this(0); 40 } 41 42 /** 43 * Create a HexDumper object; use it to dump an array of bytes and return the dump as a String. 44 * @param addressOffset int; address of the first byte 45 * @param bytes byte[]; the bytes to hex-dump 46 * @return String; the hexadecimal and character dump of the <code>bytes</code> 47 */ 48 public static String hexDumper(final int addressOffset, final byte[] bytes) 49 { 50 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 51 try 52 { 53 new HexDumper(addressOffset).setOutputStream(baos).append(bytes).flush(); 54 return baos.toString("UTF-8"); 55 } 56 catch (IOException exception) 57 { 58 // Cannot happen because ByteOutputStream.write(byte[]) cannot fail and UTF-8 exists 59 return ""; 60 } 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 }