001package algs55; // section 5.5 002import stdlib.*; 003/* *********************************************************************** 004 * Compilation: javac HexDump.java 005 * Execution: java HexDump < file 006 * Dependencies: BinaryIn.java 007 * Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt 008 * 009 * Reads in a binary file and writes out the bytes in hex, 16 per line. 010 * 011 * % more abra.txt 012 * ABRACADABRA! 013 * 014 * % java HexDump 16 < abra.txt 015 * 41 42 52 41 43 41 44 41 42 52 41 21 016 * 96 bits 017 * 018 * % hexdump < abra.txt 019 * 020 * % od -t x1 < abra.txt 021 * 0000000 41 42 52 41 43 41 44 41 42 52 41 21 022 * 0000014 023 * 024 *************************************************************************/ 025 026public class HexDump { 027 private static BinaryIn binaryIn; 028 029 public static void main(String[] args) { 030 //binaryIn = new BinaryIn ("data/abra.txt"); 031 //binaryIn = new BinaryIn ("abra.bin"); 032 //binaryIn = new BinaryIn ("genomeTiny.bin"); 033 binaryIn = new BinaryIn ("4runsOut.bin"); 034 args = new String[] { "16" }; 035 036 int BYTES_PER_LINE = 16; 037 if (args.length == 1) { 038 BYTES_PER_LINE = Integer.parseInt(args[0]); 039 } 040 041 int i; 042 for (i = 0; !binaryIn.isEmpty(); i++) { 043 if (BYTES_PER_LINE == 0) { binaryIn.readChar(); continue; } 044 if (i == 0) StdOut.format(""); 045 else if (i % BYTES_PER_LINE == 0) StdOut.format("\n", i); 046 else StdOut.print(" "); 047 char c = binaryIn.readChar(); 048 StdOut.format("%02x", c & 0xff); 049 } 050 if (BYTES_PER_LINE != 0) StdOut.println(); 051 StdOut.println((i*8) + " bits"); 052 } 053}