Skip to content

Instantly share code, notes, and snippets.

@geekman
Created March 26, 2013 06:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geekman/5243537 to your computer and use it in GitHub Desktop.
Save geekman/5243537 to your computer and use it in GitHub Desktop.
simple hex dump in Java
public static String hexdump(byte[] data) {
final int perRow = 16;
final String hexChars = "0123456789ABCDEF";
StringBuilder dump = new StringBuilder();
StringBuilder chars = null;
for (int i = 0; i < data.length; i++) {
int offset = i % perRow;
if (offset == 0) {
chars = new StringBuilder();
dump.append(String.format("%04x", i))
.append(" ");
}
int b = data[i] & 0xFF;
dump.append(hexChars.charAt(b >>> 4))
.append(hexChars.charAt(b & 0xF))
.append(' ');
chars.append((char) ((b >= ' ' && b <= '~') ? b : '.'));
if (i == data.length - 1 || offset == perRow - 1) {
for (int j = perRow - offset - 1; j > 0; j--)
dump.append("-- ");
dump.append(" ")
.append(chars)
.append('\n');
}
}
return dump.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment