2013-07-05 11 views
11

Voglio convertire un valore stringa (in esadecimale) in un indirizzo IP. Come posso farlo usando Java?Converti stringa esadecimale in indirizzo IP

valore esadecimale: 0A064156

IP: 10.6.65.86

Questo site mi dà il risultato corretto, ma non sono sicuro di come implementare questo nel mio codice.

Può essere eseguito direttamente in un XSLT?

+1

1. dividere la stringa in sottostringhe di lunghezza 2. 2. Convertire tutte le sottostringhe a dezimal. 3. Inserire punti tra tutte le sottostringhe. – Sirko

risposta

12

provare questo

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

DatatypeConverter è da serie javax.xml.bind pacchetto

+1

+1. Mi piace molto questa risposta. Non molto codice o manipolazione delle stringhe e ti dà esattamente quello che vuoi. – ARC

+0

Grazie mille! Dolce e preciso – Rg90

4

È possibile dividere il valore esadecimale in gruppi di 2 e convertirli in numeri interi.

0A = 10

06 = 06

65 = 41

86 = 56

Codice:

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

uscita:

Ip = 10.6.65.86.

+1

più votati, la tua risposta insegna effettivamente come catturare il pesce – HRgiger

0
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

È possibile utilizzare il seguente metodo:

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