Convert hexadecimal string to IP Address

2019-02-08 16:54发布

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

This site gives me the correct result, but I am not sure how to implement this in my code.

Can it be done directly in an XSLT?

6条回答
女痞
2楼-- · 2019-02-08 17:27

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;
}
查看更多
祖国的老花朵
3楼-- · 2019-02-08 17:32

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;
}
查看更多
混吃等死
4楼-- · 2019-02-08 17:33

try this

InetAddress a = InetAddress.getByAddress(DatatypeConverter.parseHexBinary("0A064156"));

DatatypeConverter is from standard javax.xml.bind package

查看更多
欢心
5楼-- · 2019-02-08 17:35

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.

查看更多
迷人小祖宗
6楼-- · 2019-02-08 17:48

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-

查看更多
唯我独甜
7楼-- · 2019-02-08 17:49
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();

}

查看更多
登录 后发表回答