Skip to content

Instantly share code, notes, and snippets.

@surajchhetry
Forked from mikeando/README.md
Created December 18, 2019 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save surajchhetry/eb5b53052043e14b128a9259d88bb4f1 to your computer and use it in GitHub Desktop.
Save surajchhetry/eb5b53052043e14b128a9259d88bb4f1 to your computer and use it in GitHub Desktop.
Output buffer as binary, similar to xxd in java

Simple XXD Style output from a ByteBuffer.

Refactored here without testing, so probably no-longer compiles - but should be a good starting point should I need it again.

public class XxdOutputter {
protected void printLineNumber(PrintStream stream, int idx) {
stream.printf("%08x:", idx);
}
protected void printHexCharOrSpace(PrintStream stream, ByteBuffer byteBuffer, int offset) {
if (offset < byteBuffer.length()) {
stream.printf("%02x", byteBuffer.get(offset));
} else {
stream.printf(" ");
}
}
protected void printHexBytes(PrintStream stream, ByteBuffer byteBuffer, int offset ) {
int bytes = byteBuffer.length();
for (int j = 0; j < 8; ++j) {
stream.printf(" ");
printHexCharOrSpace(stream, byteBuffer, offset+2*j);
printHexCharOrSpace(stream, byteBuffer, offset+2*j+1);
}
}
protected void printPrinableChars(PrintStream stream, ByteBuffer byteBuffer, int offset) {
int bytes = byteBuffer.length();
for (int j = 0; j < 16; ++j) {
if (offset + j < bytes) {
byte b = byteBuffer.get(offset + j);
if (Character.isISOControl((char) b)) {
stream.printf(".");
} else {
stream.append((char) b);
}
} else {
stream.append(' ');
}
}
}
public String xxdStyleByteOutput(ByteBuffer byteBuffer, int startOffset, int length) {
ByteArrayOutputStream bstream = new ByteArrayOutputStream();
try (PrintStream stream = new PrintStream(bstream)) {
for (int idx = 0; idx < bytes; idx += 16) {
printLineNumber(idx + startOffset);
printHexBytes(stream, byteBuffer, idx + startOffset);
stream.printf(" ");
printPrintableCharacters(stream, bytBuffer, idx + startOffset);
stream.printf("\n");
}
}
return bstream.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment