Java Hex Dump hexDump(byte[] data)

Here you can find the source of hexDump(byte[] data)

Description

Dumps binary data, presending raw bytes and their character equivalents.

License

Open Source License

Parameter

Parameter Description
data the data to be displayed

Declaration

public static String hexDump(byte[] data) 

Method Source Code


//package com.java2s;
/*/*from  w  w  w.j ava2  s  .  co  m*/
* Copyright (c) 2000 - 2005 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:  
*
*/

import java.io.PrintWriter;
import java.io.StringWriter;

import java.util.BitSet;

public class Main {
    public final static String NULL = "null";
    /** A table of hex digits */
    private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };
    private static BitSet printChars = null;
    private static final String PRINTABLE = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

    /**
     * Dumps binary data, presending raw bytes and their character equivalents.
     * The output looks like this:
     * <pre>
     * 00000000  01 04 04 00 7F E7 55 03 6F 76 65 72 76 69 65 77  ......U.overview
     * 00000010  00 36 03 4F 76 65 72 76 69 65 77 00 01 60 64 03  .6.Overview..`d.
     * 00000020  57 68 61 74 20 69 73 20 57 41 50 3F 00 01 26 26  What is WAP?..&&
     * </pre>
     *
     * @param data the data to be displayed
     */
    public static String hexDump(byte[] data) {
        if (data == null) {
            return NULL;
        } else {
            StringWriter w = new StringWriter();
            hexDump(0, new PrintWriter(w), data, 0, data.length);
            return w.toString();
        }
    }

    /**
     * Dumps binary data, presending raw bytes and their character equivalents.
     * The output looks like this:
     * <pre>
     * 00000000  01 04 04 00 7F E7 55 03 6F 76 65 72 76 69 65 77  ......U.overview
     * 00000010  00 36 03 4F 76 65 72 76 69 65 77 00 01 60 64 03  .6.Overview..`d.
     * 00000020  57 68 61 74 20 69 73 20 57 41 50 3F 00 01 26 26  What is WAP?..&&
     * </pre>
     *
     * @param w consumes the output
     * @param data the data to be displayed
     */
    public static void hexDump(PrintWriter w, byte[] data) {
        if (data != null) {
            hexDump(0, w, data, 0, data.length);
        }
    }

    /**
     * Dumps binary data, presending raw bytes and their character equivalents.
     * The output looks like this:
     * <pre>
     * 00000000  01 04 04 00 7F E7 55 03 6F 76 65 72 76 69 65 77  ......U.overview
     * 00000010  00 36 03 4F 76 65 72 76 69 65 77 00 01 60 64 03  .6.Overview..`d.
     * 00000020  57 68 61 74 20 69 73 20 57 41 50 3F 00 01 26 26  What is WAP?..&&
     * </pre>
     *
     * @param w consumes the output
     * @param data the data to be displayed
     */
    public static void hexDump(PrintWriter w, byte[] data, int off, int len) {
        if (data != null) {
            hexDump(0, w, data, off, len);
        }
    }

    /**
     * Dumps binary data, presending raw bytes and their character equivalents.
     * The output looks like this:
     * <pre>
     * 00000000  01 04 04 00 7F E7 55 03 6F 76 65 72 76 69 65 77  ......U.overview
     * 00000010  00 36 03 4F 76 65 72 76 69 65 77 00 01 60 64 03  .6.Overview..`d.
     * 00000020  57 68 61 74 20 69 73 20 57 41 50 3F 00 01 26 26  What is WAP?..&&
     * </pre>
     *
     * @param start start "offset" (the left column)
     * @param w consumes the output
     * @param data the data to be displayed
     */
    public static void hexDump(int start, PrintWriter w, byte[] data) {
        if (data != null) {
            hexDump(start, w, data, 0, data.length);
        }
    }

    /**
     * Dumps binary data, presending raw bytes and their character equivalents.
     * The output looks like this:
     * <pre>
     * 00000000  01 04 04 00 7F E7 55 03 6F 76 65 72 76 69 65 77  ......U.overview
     * 00000010  00 36 03 4F 76 65 72 76 69 65 77 00 01 60 64 03  .6.Overview..`d.
     * 00000020  57 68 61 74 20 69 73 20 57 41 50 3F 00 01 26 26  What is WAP?..&&
     * </pre>
     *
     * @param start start "offset" (the left column)
     * @param w consumes the output
     * @param data the data to be displayed
     * @param off the start offset in the data array
     * @param len number of bytes to dump.
     */
    public static void hexDump(int start, PrintWriter w, byte[] data, int off, int len) {
        if (data != null || len != 0) {
            int rowSize = 16; // Number of bytes to show in a row
            int addrBits = (((off + len) < 0x10000) ? 16 : ((off + len) < 0x1000000 ? 24 : 32));

            int nRows = (len + rowSize - 1) / rowSize;
            for (int row = 0; row < nRows; row++) {

                // Create row address label:
                int addr = start + row * rowSize;
                for (int i = addrBits - 4; i >= 0; i -= 4)
                    w.print(toHex(addr >> i));
                w.print(" ");

                // Show the bytes plus their renderable characters:
                for (int offset = 0; offset < rowSize; offset++) {
                    int index = (row * rowSize) + offset;
                    if (index < len) {
                        // Separate bytes by a single space
                        w.print(" ");
                        int b = data[off + index];
                        w.print(toHex(b >> 4)); // upper nibble
                        w.print(toHex(b)); // lower nibblebble
                    } else {
                        // Pad partial line with spaces
                        // so that the character version will align correctly:
                        w.print("   ");
                    }
                }
                // Add character version of row data:
                w.print("  ");
                for (int offset = 0; offset < rowSize; offset++) {
                    int index = (row * rowSize) + offset;
                    if (index < data.length) {
                        char ch = (char) data[off + index];
                        if (isPrintable(ch)) {
                            w.print(ch); // displayable character
                        } else {
                            w.print('.');
                        }
                    } else {
                        // Pad partial line with spaces
                        // so that all lines have equal length
                        w.print(' ');
                    }
                }
                w.println();
            }
        }
    }

    /**
     * Returns the string representation of a byte array.
     * @param bytes the byte array
     * @return the string representation of a byte array.
     */
    public static String toString(byte[] bytes) {
        return toString(bytes, "[", ",", "]");
    }

    /**
     * Returns the string representation of a byte array.
     * @param bytes the byte array
     * @param beg string to begin the string with
     * @param sep string to separate bytes
     * @param end string to terminate the string with
     * @return the string representation of a byte array.
     */
    public static String toString(byte[] bytes, String beg, String sep, String end) {
        return toString(null, bytes, beg, sep, end).toString();
    }

    /**
     * Returns the string representation of a byte array.
     * @param sb the StringBuffer
     * @param bytes the byte array
     * @param begin string to begin the string with
     * @param sep string to separate bytes from each other
     * @param end string to terminate the string with
     * @return the string representation of a byte array.
     */
    public static StringBuffer toString(StringBuffer sb, byte[] bytes, String begin, String sep, String end) {
        if (bytes != null) {
            if (sb == null) {
                // allocate string buffer of exact size to avoid reallocation
                int len = bytes.length;
                int n1 = ((begin == null) ? 0 : begin.length());
                int n2 = ((sep == null) ? 0 : sep.length());
                int n3 = ((end == null) ? 0 : end.length());
                sb = new StringBuffer(2 * len + n2 * (len - 1) + n1 + n3);
            }
            if (begin != null)
                sb.append(begin);
            for (int i = 0; i < bytes.length; i++) {
                if (i > 0 && sep != null)
                    sb.append(sep);
                toHexString(sb, bytes[i]);
            }
            if (end != null)
                sb.append(end);
        } else {
            if (sb == null) {
                sb = new StringBuffer(NULL);
            } else {
                sb.append(NULL);
            }
        }
        return sb;
    }

    /**
     * Converts array of objects into a comma separated string enclosed
     * into curly brackets.
     */
    public static String toString(Object[] array) {
        return toString(null, array).toString();
    }

    /**
     * Converts array of objects into a comma separated string enclosed
     * into curly brackets and appends it to a StringBuffer.
     *
     * @param sb the destination buffer
     * @param array array of objects
     */
    public static StringBuffer toString(StringBuffer sb, Object[] array) {
        return toString(sb, array, "{", ",", "}");
    }

    /**
     * Converts array of objects into a string enclosed into curly brackets.
     *
     * @param array array of objects
     * @param sep string to separate bytes from each other
     */
    public static String toString(Object[] array, String sep) {
        return toString(array, "{", sep, "}");
    }

    /**
     * Converts array of objects into a comma separated string enclosed
     * into curly brackets.
     *
     * @param array array of objects
     * @param begin string to begin the string with
     * @param end string to terminate the string with
     */
    public static String toString(Object[] array, String begin, String end) {
        return toString(array, begin, ",", end);
    }

    /**
     * Converts array of objects into a string.
     *
     * @param array array of objects
     * @param begin string to begin the string with
     * @param sep string to separate bytes from each other
     * @param end string to terminate the string with
     */
    public static String toString(Object[] array, String begin, String sep, String end) {
        return toString(null, array, begin, sep, end).toString();
    }

    /**
     * Converts array of objects into a string and appends it to
     * a StringBuffer
     *
     * @param array array of objects
     * @param begin string to begin the string with
     * @param sep string to separate bytes from each other
     * @param end string to terminate the string with
     */
    public static StringBuffer toString(StringBuffer sb, Object[] array, String begin, String sep, String end) {
        if (array != null) {
            if (sb == null)
                sb = new StringBuffer(array.length * 5 + 2); // guess
            if (begin != null)
                sb.append(begin);
            for (int i = 0; i < array.length; i++) {
                if (i > 0 && sep != null)
                    sb.append(sep);
                if (array[i] == null) {
                    sb.append(NULL);
                } else {
                    sb.append(array[i].toString());
                }
            }
            if (end != null)
                sb.append(end);
        } else {
            if (sb == null) {
                sb = new StringBuffer(NULL);
            } else {
                sb.append(NULL);
            }
        }
        return sb;
    }

    /**
     * Converts a nibble to a hex character
     * @param   nibble   the nibble to convert.
     * @return the hex character
     */
    private static char toHex(int nibble) {
        return hexDigit[(nibble & 0xF)];
    }

    /**
     * Returns <code>true</code> if characters may be considered "printable"
     */
    public static boolean isPrintable(char ch) {
        if (!Character.isISOControl(ch)) {
            if (printChars == null)
                initPrintChars();
            return printChars.get(ch);
        }
        return false;
    }

    /**
     * Returns the string representation of a byte.
     * @param b the byte
     * @return the string representation of a byte.
     */
    public static String toHexString(byte b) {
        return toHexString(null, b).toString();
    }

    /**
     * Returns the string representation of a byte array.
     * @param b the byte array
     * @return the string representation of a byte array.
     */
    public static String toHexString(byte[] b) {
        return toString(b, null, " ", null);
    }

    /**
     * Appends the string representation of a byte to the string buffer.
     * @param sb the StringBuffer
     * @param b the byte
     * @return the string buffer
     */
    public static StringBuffer toHexString(StringBuffer sb, byte b) {
        if (sb == null)
            sb = new StringBuffer(2);
        sb.append(toHex(b >> 4)); // upper nibble
        sb.append(toHex(b)); // lower nibble
        return sb;
    }

    /**
     * Initialize bitset for {@link isPrintable()}
     */
    private static synchronized void initPrintChars() {
        if (printChars == null) {
            printChars = new BitSet(128);
            for (int i = 0; i < PRINTABLE.length(); i++) {
                printChars.set(PRINTABLE.charAt(i));
            }
        }
    }
}

Related

  1. hexdump(byte[] bytes, OutputStream out)
  2. hexDump(InputStream is, OutputStream os)
  3. hexDump(InputStream is, PrintStream ps, int maxRead, int bytesPerLine)
  4. hexDump(PrintStream out, String s, byte b[], int n)
  5. hexDump(String prompt, byte[] bs)