Skip to content

Instantly share code, notes, and snippets.

@jen20
Created May 19, 2015 14:33
Show Gist options
  • Save jen20/906db194bd97c14d91df to your computer and use it in GitHub Desktop.
Save jen20/906db194bd97c14d91df to your computer and use it in GitHub Desktop.
Dump byte array in hex dump format in Java
import java.io.UnsupportedEncodingException;
public final class HexDumpUtil {
public static String formatHexDump(byte[] array, int offset, int length) {
final int width = 16;
StringBuilder builder = new StringBuilder();
for (int rowOffset = offset; rowOffset < offset + length; rowOffset += width) {
builder.append(String.format("%06d: ", rowOffset));
for (int index = 0; index < width; index++) {
if (rowOffset + index < array.length) {
builder.append(String.format("%02x ", array[rowOffset + index]));
} else {
builder.append(" ");
}
}
if (rowOffset < array.length) {
int asciiWidth = Math.min(width, array.length - rowOffset);
builder.append(" | ");
try {
builder.append(new String(array, rowOffset, asciiWidth, "UTF-8").replaceAll("\r\n", " ").replaceAll("\n", " "));
} catch (UnsupportedEncodingException ignored) {
//If UTF-8 isn't available as an encoding then what can we do?!
}
}
builder.append(String.format("%n"));
}
return builder.toString();
}
}
@chumpa
Copy link

chumpa commented Mar 2, 2019

thank you for code

@hrstoyanov
Copy link

Thanks for sharing the code! One improvement you can do is to pre-allocate the string builder size, so you does not expand as it builds.

@OlegKyiashko
Copy link

replace line 24 to
builder.append(new String(array, rowOffset, asciiWidth, "US-ASCII").replaceAll("[^\\x20-\\x7E]", "."));

will print pretty hexdump

@MYG63
Copy link

MYG63 commented Jan 22, 2024

replace line 24 to builder.append(new String(array, rowOffset, asciiWidth, "US-ASCII").replaceAll("[^\\x20-\\x7E]", "."));

will print pretty hexdump

You should not use fixed ASCII number representations. On other platforms with different codepages that will not work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment