Created
May 19, 2015 14:33
-
-
Save jen20/906db194bd97c14d91df to your computer and use it in GitHub Desktop.
Dump byte array in hex dump format in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
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.
replace line 24 to
builder.append(new String(array, rowOffset, asciiWidth, "US-ASCII").replaceAll("[^\\x20-\\x7E]", "."));
will print pretty hexdump
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
thank you for code