Convert hexadecimal string to IP Address

倖福魔咒の 提交于 2019-12-18 15:12:09

问题


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?


回答1:


try this

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

DatatypeConverter is from standard javax.xml.bind package




回答2:


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.




回答3:


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();

}




回答4:


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;
}



回答5:


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;
}



回答6:


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-



来源:https://stackoverflow.com/questions/17489404/convert-hexadecimal-string-to-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!