Refactored here without testing, so probably no-longer compiles - but should be a good starting point should I need it again.
Last active
December 18, 2019 08:34
-
-
Save mikeando/9967092 to your computer and use it in GitHub Desktop.
Output buffer as binary, similar to xxd 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
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