From: Hendrik B. <nh...@us...> - 2010-03-03 20:30:16
|
Update of /cvsroot/arianne/unrelated-stuff/src/net/sf/arianne/tools/ipcalc In directory sfp-cvsdas-1.v30.ch3.sourceforge.com:/tmp/cvs-serv31108/src/net/sf/arianne/tools/ipcalc Added Files: IPCalc.java Log Message: converting ipaddress to hexadecimal and back --- NEW FILE: IPCalc.java --- package net.sf.arianne.tools.ipcalc; /** * IP address calculator. * * @author hendrik */ public class IPCalc { /** * adds some leading '0' to the sting until the length <i>maxDigits</i> is * reached * * @param number * the number to convert * @param maxDigits * the amount of digits expected * @return the expected number */ public static String addLeadingZeros(String number, int maxDigits) { StringBuilder result = new StringBuilder(number); while (result.length() < maxDigits) { result.insert(0, "0"); } return result.toString(); } private static String ipToHex(String address) { String[] tokens = address.split("\\."); StringBuilder res = new StringBuilder(); for (String token : tokens) { res.append(addLeadingZeros(Integer.toHexString(Integer.parseInt(token)), 2)); } return res.toString(); } private static String hexToIp(String address) { StringBuilder res = new StringBuilder(); for (int i = 0; i < 3; i++) { res.append(Integer.parseInt(address.substring(i * 2, i * 2 + 1), 16)); res.append("."); } return res.toString(); } public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: " + IPCalc.class.getName() + " ip.ad.dre.ss | hexadecimal"); System.exit(1); } String address = args[0]; if (address.indexOf(".") > -1) { System.out.println(ipToHex(address)); } else { System.out.println(hexToIp(address)); } } } |