TheLastRefuge / Jarcon

🌐 Java remote console client for Battlefield servers
0 stars 0 forks source link

Log hex dumps #3

Closed chris6366 closed 11 months ago

chris6366 commented 3 years ago
public static String getHexDump(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    int size = bytes.length;
    int width = 16;

    for(int i = 0; i < size; i += width) {
        sb.append(String.format("%04x", i)).append("\s".repeat(3));

        for(int j = 0; j < width; j++) {
            if(i + j < size) sb.append(String.format("%02x\s", bytes[i + j]));
            else sb.append("\s".repeat(3));
        }
        sb.append("\s".repeat(2));

        int length = Math.min(width, size - i);
        String ascii = new String(bytes, i, length, StandardCharsets.US_ASCII);
        sb.append(ascii.replaceAll("[^\\x21-\\x7E]", "."));

        if(i + width < size) sb.append("\n");
    }
    return sb.toString();
}

Here's a Wireshark-style hex dump util method I wrote. I don't think you're doing any byte-level decoding because of the nature of the protocol, but maybe you'll still find it useful.

ItsFlare commented 11 months ago

Neat addition, thank you!