Java Method to Output a Byte Array in HEX Dump Format

On StackOverflow, I posted code to output a byte array in a HEX dump format. I thought I should post the code here as a complete working sample.

You can download the source code from here.

You can copy the 2 methods (dumpBuffer & formatHex) to your general purpose toolkit and use them in any Java project you have. The code is pretty straightforward. The method dumpBuffer expects 2 parameters: the byte array and the width of the HEX dump. Most people like a size of 16. You can use any value that is a multiple of 16 (i.e. 32, 48, 64, etc.).

There are all kinds of reasons why you would want to dump a byte array as a HEX dump but the primary reason is probably because the byte array has binary data that when outputted with System.out.println is displayed as garbage.

/**
 * Program Name
 *  Test_HEX_Dump
 *
 * Description
 *  A simple program to demonstrate how to output a byte array as a HEX dump.
 *
 * @author Roger Lacroix
 * @version 1.0.0
 * @license Apache 2 License
 */
public class Test_HEX_Dump
{
   /**
    * The constructor
    */
   public Test_HEX_Dump()
   {
      super();
      String song = "Mary had a little lamb, Its fleece was white as snow, And every where that Mary went The lamb was sure to go; He followed her to school one day, That was against the rule, It made the children laugh and play, To see a lamb at school.";

      dumpBuffer(song.getBytes(), 16);
   }

   /**
    * Dump a byte array as a standard HEX dump output
    * @param data the entire byte array
    * @param widthSize width of the HEX dump. Must be in multiples of 16
    */
   public void dumpBuffer(byte[] data, int widthSize)
   {
      int      endPt = widthSize;
      int      len = data.length;
      byte[]   tempBuffer = new byte[widthSize];

      if ((widthSize % 16) != 0)
      {
         System.err.println("Error: widthSize value ["+widthSize+"] is not a multiple of 16.");
      }
      else
      {
         if (widthSize == 16)
         {
            System.out.println("Address  0 1 2 3  4 5 6 7  8 9 A B  C D E F  0123456789ABCDEF");
            System.out.println("------- -------- -------- -------- --------  ----------------");
         }
         else if (widthSize == 32)
         {
            System.out.println("Address  0 1 2 3  4 5 6 7  8 9 A B  C D E F  0 1 2 3  4 5 6 7  8 9 A B  C D E F  0123456789ABCDEF0123456789ABCDEF");
            System.out.println("------- -------- -------- -------- -------- -------- -------- -------- --------  --------------------------------");
         }

         for (int i=0; i < len; i+=widthSize)
         {
            if (i+widthSize >= len)
               endPt = len - i;

            for (int j=0; j < endPt; j++)
               tempBuffer[j] = data[i+j];

            System.out.println(formatHex(tempBuffer, (i+widthSize < len?widthSize:len-i), i, widthSize ));
         }
      }
   }

   /**
    * Format an array of bytes into a hex display
    * @param src a portion of the byte array
    * @param len length of this part of the byte array
    * @param index location of current position in data
    * @param width width of the HEX dump
    * @return
    */
   private String formatHex(byte[] src, int lenSrc, int index, int width)
   {
      int i, j;
      int g = width / 4; /* number of groups of 4 bytes */
      int d = g * 9;     /* hex display width */
      StringBuffer sb = new StringBuffer();

      if ( (src == null) ||
           (lenSrc < 1)  || (lenSrc > width) ||
           (index < 0)   ||
           (g % 4 != 0)  ||   /* only allow width of 16 / 32 / 48 etc. */
           (d < 36) )
      {
         return "";
      }

      String hdr = Integer.toHexString(index).toUpperCase();
      if (hdr.length() <= 6)
         sb.append("000000".substring(0, 6 - hdr.length()) + hdr + ": ");
      else
         sb.append(hdr + ": ");

      /* hex display 4 by 4 */
      for(i=0; i < lenSrc; i++)
      {
         sb.append(""+"0123456789ABCDEF".charAt((src[i]) >> 4) + "0123456789ABCDEF".charAt((src[i] & 0x0F)));

         if (((i+1) % 4) == 0)
            sb.append(" ");
      }

      /* blank fill hex area if we do not have "width" bytes */
      if (lenSrc < width)
      {
         j = d - (lenSrc*2) - (lenSrc / 4);
         for(i=0; i < j; i++)
            sb.append(" ");
      }

      /* character display */
      sb.append(" ");
      for (i=0; i < lenSrc; i++)
      {
         if(Character.isISOControl((char)src[i]))
            sb.append(".");
         else
            sb.append((char)src[i]);
      }

      /* blank fill character area if we do not have "width" bytes */
      if (lenSrc < width)
      {
         j = width - lenSrc;
         for(i=0; i < j; i++)
            sb.append(" ");
      }

      return sb.toString();
   }

   /**
    * Entry point to program
    * @param args
    */
   public static void main(String[] args)
   {
      new Test_HEX_Dump();
   }
}

Here’s what the output looks like from running this sample:

Address  0 1 2 3  4 5 6 7  8 9 A B  C D E F  0123456789ABCDEF
------- -------- -------- -------- --------  ----------------
000000: 4D617279 20686164 2061206C 6974746C  Mary had a littl
000010: 65206C61 6D622C20 49747320 666C6565  e lamb, Its flee
000020: 63652077 61732077 68697465 20617320  ce was white as
000030: 736E6F77 2C20416E 64206576 65727920  snow, And every
000040: 77686572 65207468 6174204D 61727920  where that Mary
000050: 77656E74 20546865 206C616D 62207761  went The lamb wa
000060: 73207375 72652074 6F20676F 3B204865  s sure to go; He
000070: 20666F6C 6C6F7765 64206865 7220746F   followed her to
000080: 20736368 6F6F6C20 6F6E6520 6461792C   school one day,
000090: 20546861 74207761 73206167 61696E73   That was agains
0000A0: 74207468 65207275 6C652C20 4974206D  t the rule, It m
0000B0: 61646520 74686520 6368696C 6472656E  ade the children
0000C0: 206C6175 67682061 6E642070 6C61792C   laugh and play,
0000D0: 20546F20 73656520 61206C61 6D622061   To see a lamb a
0000E0: 74207363 686F6F6C 2E                 t school.

Regards,
Roger Lacroix
Capitalware Inc.

This entry was posted in HPE NonStop, IBM i (OS/400), Java, JMS, Linux, macOS (Mac OS X), Open Source, Programming, Raspberry Pi, Unix, Windows.

2 Responses to Java Method to Output a Byte Array in HEX Dump Format