Java Byte Array Dump dump(byte[] bytes, int offset, int byteslen)

Here you can find the source of dump(byte[] bytes, int offset, int byteslen)

Description

Dump to string using a debugger-like format - both hex and ascii.

License

LGPL

Declaration

public static String dump(byte[] bytes, int offset, int byteslen) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

public class Main {
    private static final int MAX_BYTE_PLUS1 = 256;

    /**//  w  w  w  .  j  av  a2 s.c o m
     * Dump to string using a debugger-like format - both hex and ascii.
     */
    public static String dump(byte[] bytes, int offset, int byteslen) {
        final StringBuffer b = new StringBuffer();

        final int width = 32;
        int len = width;
        while (offset < byteslen) {
            int remainder = 0;

            if (offset + len > byteslen) {
                len = byteslen - offset;
                remainder = width - len;
            }
            b.append(byteArrayToHexString(bytes, len, offset));
            for (int i = 0; i < remainder; ++i) {
                b.append("  ");
            }
            b.append(" | ");
            for (int i = 0; i < len; ++i) {
                byte c = bytes[offset + i];
                if (c >= ' ' && c <= '~') {
                    b.append((char) c);
                } else
                    b.append('.');
            }

            b.append('\n');

            offset += len;

        }
        return b.toString();
    }

    public static String byteArrayToHexString(byte[] array) {
        return byteArrayToHexString(array, array.length);
    }

    public static String byteArrayToHexString(byte[] array, int len) {
        return byteArrayToHexString(array, len, 0);

    }

    public static String byteArrayToHexString(byte[] array, int len,
            int offset) {
        StringBuffer b = new StringBuffer();
        for (int i = 0; i < len; ++i) {
            String byteStr = Integer.toHexString(uByteToInt(array[offset
                    + i]));
            if (byteStr.length() == 1)
                byteStr = "0" + byteStr;
            b.append(byteStr);
        }
        return b.toString();
    }

    public static int uByteToInt(byte b) {
        if (b >= 0)
            return b;
        else
            return MAX_BYTE_PLUS1 + b;
    }
}

Related

  1. dump(byte[] array)
  2. dump(byte[] array)
  3. dump(byte[] buff, int size, boolean asBits)
  4. dump(byte[] buffer)
  5. dump(byte[] bytes)
  6. dump(byte[] data, int offset, int length)
  7. dump(byte[] data, int pos, int length)
  8. dump(byte[] mem, int start, int len)
  9. dump(byte[] rec)