Convert hexadecimal string to IP Address

后端 未结 6 1560
囚心锁ツ
囚心锁ツ 2021-01-02 03:11

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<

相关标签:
6条回答
  • 2021-01-02 03:34

    try this

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

    DatatypeConverter is from standard javax.xml.bind package

    0 讨论(0)
  • 2021-01-02 03:38

    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.

    0 讨论(0)
  • 2021-01-02 03:38

    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;
    }
    
    0 讨论(0)
  • 2021-01-02 03:39

    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-

    0 讨论(0)
  • 2021-01-02 03:51
    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();
    

    }

    0 讨论(0)
  • 2021-01-02 03:57

    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;
    }
    
    0 讨论(0)
提交回复
热议问题