IP.java


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


/******************************************************************************
 *  Compilation:  javac IP.java
 *  Execution:    java IP 010100000001000000000000000000
 *
 *  Takes a 32-bit string as a command-line argument and prints the
 *  corresponding IP address using dotted decimal notation.
 *
 *  java IP 01010000000100000000000000000001
 *  80.16.0.1
 *
 ******************************************************************************/

public class IP {
    private static final int BITS_PER_BYTE = 8;

    public static void main(String[] args) {
        String ip = args[0];
        if (ip.length() % BITS_PER_BYTE != 0)
            throw new IllegalArgumentException("argument must have a multiple of 8 bits");

        for (int i = 0; i < ip.length(); i += BITS_PER_BYTE) {
            String bits = ip.substring(i, i+BITS_PER_BYTE);
            int decimal = Integer.parseInt(bits, 2);
            if (i != 0) StdOut.print(".");
            StdOut.print(decimal);
        }
        StdOut.println();
    }
}


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