    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.io;
    018
    019import java.io.IOException;
    020import java.io.OutputStream;
    021import java.nio.charset.Charset;
    022
    023/**
    024 * Dumps data in hexadecimal format.
    025 * <p>
    026 * Provides a single function to take an array of bytes and display it
    027 * in hexadecimal form.
    028 * <p>
    029 * Origin of code: POI.
    030 *
    031 */
    032public class HexDump {
    033
    034    /**
    035     * Instances should NOT be constructed in standard programming.
    036     */
    037    public HexDump() {
    038    }
    039
    040    /**
    041     * Dump an array of bytes to an OutputStream. The output is formatted
    042     * for human inspection, with a hexadecimal offset followed by the
    043     * hexadecimal values of the next 16 bytes of data and the printable ASCII
    044     * characters (if any) that those bytes represent printed per each line
    045     * of output.
    046     * <p>
    047     * The offset argument specifies the start offset of the data array
    048     * within a larger entity like a file or an incoming stream. For example,
    049     * if the data array contains the third kibibyte of a file, then the
    050     * offset argument should be set to 2048. The offset value printed
    051     * at the beginning of each line indicates where in that larger entity
    052     * the first byte on that line is located.
    053     * <p>
    054     * All bytes between the given index (inclusive) and the end of the
    055     * data array are dumped.
    056     *
    057     * @param data  the byte array to be dumped
    058     * @param offset  offset of the byte array within a larger entity
    059     * @param stream  the OutputStream to which the data is to be
    060     *               written
    061     * @param index initial index into the byte array
    062     *
    063     * @throws IOException is thrown if anything goes wrong writing
    064     *         the data to stream
    065     * @throws ArrayIndexOutOfBoundsException if the index is
    066     *         outside the data array's bounds
    067     * @throws IllegalArgumentException if the output stream is null
    068     */
    069
    070    public static void dump(final byte[] data, final long offset,
    071                            final OutputStream stream, final int index)
    072            throws IOException, ArrayIndexOutOfBoundsException,
    073            IllegalArgumentException {
    074
    075        if (index < 0 || index >= data.length) {
    076            throw new ArrayIndexOutOfBoundsException(
    077                    "illegal index: " + index + " into array of length "
    078                    + data.length);
    079        }
    080        if (stream == null) {
    081            throw new IllegalArgumentException("cannot write to nullstream");
    082        }
    083        long display_offset = offset + index;
    084        final StringBuilder buffer = new StringBuilder(74);
    085
    086        for (int j = index; j < data.length; j += 16) {
    087            int chars_read = data.length - j;
    088
    089            if (chars_read > 16) {
    090                chars_read = 16;
    091            }
    092            dump(buffer, display_offset).append(' ');
    093            for (int k = 0; k < 16; k++) {
    094                if (k < chars_read) {
    095                    dump(buffer, data[k + j]);
    096                } else {
    097                    buffer.append("  ");
    098                }
    099                buffer.append(' ');
    100            }
    101            for (int k = 0; k < chars_read; k++) {
    102                if (data[k + j] >= ' ' && data[k + j] < 127) {
    103                    buffer.append((char) data[k + j]);
    104                } else {
    105                    buffer.append('.');
    106                }
    107            }
    108            buffer.append(EOL);
    109            // make explicit the dependency on the default encoding
    110            stream.write(buffer.toString().getBytes(Charset.defaultCharset()));
    111            stream.flush();
    112            buffer.setLength(0);
    113            display_offset += chars_read;
    114        }
    115    }
    116
    117    /**
    118     * The line-separator (initializes to "line.separator" system property.
    119     */
    120    public static final String EOL =
    121            System.getProperty("line.separator");
    122    private static final char[] _hexcodes =
    123            {
    124                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    125                'A', 'B', 'C', 'D', 'E', 'F'
    126            };
    127    private static final int[] _shifts =
    128            {
    129                28, 24, 20, 16, 12, 8, 4, 0
    130            };
    131
    132    /**
    133     * Dump a long value into a StringBuilder.
    134     *
    135     * @param _lbuffer the StringBuilder to dump the value in
    136     * @param value  the long value to be dumped
    137     * @return StringBuilder containing the dumped value.
    138     */
    139    private static StringBuilder dump(final StringBuilder _lbuffer, final long value) {
    140        for (int j = 0; j < 8; j++) {
    141            _lbuffer
    142                    .append(_hexcodes[(int) (value >> _shifts[j]) & 15]);
    143        }
    144        return _lbuffer;
    145    }
    146
    147    /**
    148     * Dump a byte value into a StringBuilder.
    149     *
    150     * @param _cbuffer the StringBuilder to dump the value in
    151     * @param value  the byte value to be dumped
    152     * @return StringBuilder containing the dumped value.
    153     */
    154    private static StringBuilder dump(final StringBuilder _cbuffer, final byte value) {
    155        for (int j = 0; j < 2; j++) {
    156            _cbuffer.append(_hexcodes[value >> _shifts[j + 6] & 15]);
    157        }
    158        return _cbuffer;
    159    }
    160
    161}