Java Byte to Hex bytesToPrettyHex(byte[] data)

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

Description

bytes To Pretty Hex

License

Open Source License

Declaration

public static String bytesToPrettyHex(byte[] data) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String bytesToPrettyHex(byte[] data) {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            buffer.append(String.format("%02x ", data[i]));

            if (((i + 1) % 16) == 0) {
                buffer.append("| ");

                for (int j = i - 15; j <= i; j++)
                    buffer.append(getPrintableChar((char) data[j]));

                buffer.append(" |\n");
            } else if (i + 1 == data.length) {
                for (int j = i + 1; j % 16 != 0; j++)
                    buffer.append("   ");

                buffer.append("| ");

                for (int j = i - (i % 16); j <= i; j++)
                    buffer.append(getPrintableChar((char) data[j]));

                for (int j = i + 1; j % 16 != 0; j++)
                    buffer.append(' ');

                buffer.append(" |\n");
            }//from w  w w. java  2 s . c o  m
        }
        return buffer.toString();
    }

    public static char getPrintableChar(char c) {
        if (c == '\r' || c == '\n' || c == '\t')
            return ' ';
        else if (c >= ' ' && c <= '~')
            return c;
        else
            return '.';
    }
}

Related

  1. Bytes2HexString(byte[] b)
  2. bytesToHex(byte b)
  3. bytesToHexs(byte[] buf)
  4. bytesToLowerCaseHex(byte[] data)
  5. bytesToModHex(final byte[] inputBytes)
  6. bytesToReadableHexStr(byte[] msg)
  7. bytesToUpperCaseHex(byte[] b)
  8. byteToHex(byte a)
  9. byteToHex(byte b)