001package algs55; // section 5.5
002import stdlib.*;
003/* ***********************************************************************
004 *  Compilation:  javac BinaryDump.java
005 *  Execution:    java BinaryDump N < 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 bits, N per line.
010 *
011 *  % more abra.txt
012 *  ABRACADABRA!
013 *
014 *  % java BinaryDump 16 < abra.txt
015 *  0100000101000010
016 *  0101001001000001
017 *  0100001101000001
018 *  0100010001000001
019 *  0100001001010010
020 *  0100000100100001
021 *  96 bits
022 *
023 *************************************************************************/
024
025public class BinaryDump {
026        // Note: Code from textbook uses BinaryStdIn. I've refactored it to use BinaryIn.
027        // The BinaryIn/BinaryOut code is not very well tested, so if you find problems
028        // with the code in this section, you should look for bugs in those classes first.
029        private static BinaryIn binaryIn;
030
031        public static void main(String[] args) {
032                binaryIn = new BinaryIn ("/tmp/abra.bin");
033                args = new String[] { "60" };
034
035                int BITS_PER_LINE = 16;
036                if (args.length == 1) {
037                        BITS_PER_LINE = Integer.parseInt(args[0]);
038                }
039
040                int count;
041                for (count = 0; !binaryIn.isEmpty(); count++) {
042                        if (BITS_PER_LINE == 0) { binaryIn.readBoolean(); continue; }
043                        else if (count != 0 && count % BITS_PER_LINE == 0) StdOut.println();
044                        if (binaryIn.readBoolean()) StdOut.print(1);
045                        else                           StdOut.print(0);
046                }
047                if (BITS_PER_LINE != 0) StdOut.println();
048                StdOut.println(count + " bits");
049        }
050}