HammingEncoder.java


Below is the syntax highlighted version of HammingEncoder.java from §6.1 Data Representations.


/******************************************************************************
 *  Compilation:  javac HammingEncoder.java StdIn.java
 *  Execution:    java HammingEncoder < all4.txt
 *
 *  Read in sequences of 4 bits at a time from stdin, compute
 *  3 parity bits for Hamming code, and print resulting 7 bits
 *  to stdout.
 *
 *
 ******************************************************************************/

public class HammingEncoder {

    // return an integer corresponding to the 4 digit hex string
    public static int fromHex(String s) {
        return Integer.parseInt(s, 16)  & 0xFFFF;
    }

    public static void main(String[] args) {
        while (!StdIn.isEmpty()) {
            int m1 = fromHex(StdIn.readString());
            if (m1 == 0xFFFF) break;
            int m2 = fromHex(StdIn.readString());
            int m3 = fromHex(StdIn.readString());
            int m4 = fromHex(StdIn.readString());

            // compute parity bits
            int p1 = m1 ^ m2 ^ m4;
            int p2 = m1 ^ m3 ^ m4;
            int p3 = m2 ^ m3 ^ m4;

            // print results
            StdOut.print(m1 + " " + m2 + " " + m3 + " " + m4 + " ");
            StdOut.print(p1 + " " + p2 + " " + p3);
            StdOut.println();
        }
    }
}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:32:25 EDT 2022.