-- Working off of @rofl's other suggestion, this is 25% faster on my machine than your fast method, including the time to populate the map. It does consume more memory, and it eagerly maps numbers which may not be used. It is less elegant than @rofl's suggestion, and possibly slower, but I find it easier to read.
private static final String[] PAD_ZEROS =
new String[] {
"00000000",
"0000000",
"000000",
"00000",
"0000",
"000",
"00",
"0",
""
};
private static final Map<String, String> MAP =
new HashMap<String, String>(256);
private static void populateMap() {
for (int i = 0; i < 256; i++) {
final String binaryString = Integer.toBinaryString(i);
MAP.put(
Integer.toString(i),
PAD_ZEROS[binaryString.length()] + binaryString);
}
}
public static String faster(final String ip) {
final StringBuilder result = new StringBuilder(32);
final String octals[] = ip.split("\\.");
for (final String octal: octals) {
result.append(MAP.get(octal));
}
return result.toString();
}