I want to convert a string value (in hexadecimal) to an IP Address. How can I do it using Java?
Hex value: 0A064156
IP: 10.6.65.86
<
try this
InetAddress a = InetAddress.getByAddress(DatatypeConverter.parseHexBinary("0A064156"));
DatatypeConverter is from standard javax.xml.bind
package
You can split your hex value in groups of 2 and then convert them to integers.
0A = 10
06 = 06
65 = 41
86 = 56
Code:
String hexValue = "0A064156";
String ip = "";
for(int i = 0; i < hexValue.length(); i = i + 2) {
ip = ip + Integer.valueOf(hexValue.subString(i, i+2), 16) + ".";
}
System.out.println("Ip = " + ip);
Output:
Ip = 10.6.65.86.
The accepted answer has a requirement that, the hex must be even-length. Here is my answer:
private String getIpByHex(String hex) {
Long ipLong = Long.parseLong(hex, 16);
String ipString = String.format("%d.%d.%d.%d", ipLong >> 24,
ipLong >> 16 & 0x00000000000000FF,
ipLong >> 8 & 0x00000000000000FF,
ipLong & 0x00000000000000FF);
return ipString;
}
You can split it 2 characters, and then use Integer.parse(string, radix) to convert to integer values
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String,int)
UPDATE: Link for newer documentation: https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#parseInt-java.lang.String-int-
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for( int i=0; i<hex.length()-1; i+=2 ){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
temp.append(decimal);
temp.append(".");
}
System.out.println("Decimal : " + temp.toString());
return sb.toString();
}
You can use the following method:
public static String convertHexToIP(String hex)
{
String ip= "";
for (int j = 0; j < hex.length(); j+=2) {
String sub = hex.substring(j, j+2);
int num = Integer.parseInt(sub, 16);
ip += num+".";
}
ip = ip.substring(0, ip.length()-1);
return ip;
}