import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * Utility that dumps out a binary file as hex. */ public class Xxd { public static final String PAD = "00000000"; public static String leftPad(String value, int pad) { if (value.length() < pad) { if (pad - value.length() > PAD.length()) throw new IllegalArgumentException("Cannot pad that long"); return PAD.substring(0, pad - value.length()) + value; } return value; } public static char printable(int b) { return (b >= 32 && b < 127) ? (char)b : '.'; } public static void main(String[] args) throws IOException { if (args.length < 1) System.out.println("Usage: java Xxd {filename}"); else { try { FileInputStream fis = new FileInputStream(args[0]); BufferedInputStream bis = new BufferedInputStream(fis); int offset = 0; byte[] buffer = new byte[16]; int bytes = bis.read(buffer); while (bytes > -1) { System.out.print(leftPad(Integer.toHexString(offset), 8) + ": "); // Print out hex for (int i = 0; i < bytes; i++) System.out.print(leftPad(Integer.toHexString(buffer[i] & 0xff), 2) + " "); for (int i = 16; i > bytes; i--) System.out.print(" "); // Print out ASCII for (int i = 0; i < bytes; i++) System.out.print(printable(buffer[i])); System.out.println(); offset += bytes; bytes = bis.read(buffer); } System.out.println(); } catch (FileNotFoundException fnfe) { System.out.println("That file does not exist"); } } } }