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-2024 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 * @author <a href="https://www.tudelft.nl/averbraeck">Alexander Verbraeck</a> 13 * @author <a href="https://www.tudelft.nl/staff/p.knoppers/">Peter Knoppers</a> 14 */ 15 public class HexDumper extends Dumper<HexDumper> 16 { 17 18 /** 19 * Construct a new HexDumper. 20 * @param addressOffset int; address of the first byte that will be appended 21 */ 22 public HexDumper(final int addressOffset) 23 { 24 super(addressOffset); 25 addDecoder(new HexAddressDecoder(16)); 26 addDecoder(new FixedString(": ")); 27 addDecoder(new HexDecoder(16, 8)); 28 addDecoder(new FixedString(" ")); 29 addDecoder(new CharDecoder(16, 8)); 30 addDecoder(new FixedString("\n")); 31 } 32 33 /** 34 * Construct a new HexDumper. 35 */ 36 public HexDumper() 37 { 38 this(0); 39 } 40 41 /** 42 * Create a HexDumper object; use it to dump an array of bytes and return the dump as a String. 43 * @param addressOffset int; address of the first byte 44 * @param bytes byte[]; the bytes to hex-dump 45 * @return String; the hexadecimal and character dump of the <code>bytes</code> 46 */ 47 public static String hexDumper(final int addressOffset, final byte[] bytes) 48 { 49 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 50 try 51 { 52 new HexDumper(addressOffset).setOutputStream(baos).append(bytes).flush(); 53 return baos.toString("UTF-8"); 54 } 55 catch (IOException exception) 56 { 57 // Cannot happen because ByteOutputStream.write(byte[]) cannot fail and UTF-8 exists 58 return ""; 59 } 60 } 61 62 /** 63 * Create a HexDumper object with addressOffset 0; use it to dump an array of bytes and return the dump as a String. 64 * @param bytes byte[]; the bytes to hex-dump 65 * @return String; the hexadecimal and character dump of the <code>bytes</code> 66 */ 67 public static String hexDumper(final byte[] bytes) 68 { 69 return hexDumper(0, bytes); 70 } 71 72 @Override 73 public String toString() 74 { 75 return "HexDumper [super=" + super.toString() + "]"; 76 } 77 78 }