2015-12-14 29 views
5

voglio convertire una stringa esadecimale in decimale, ma ho avuto un errore nel codice seguente:java.lang.NumberFormatException la conversione di una stringa esadecimale a int

String hexValue = "23e90b831b74";  
int i = Integer.parseInt(hexValue, 16); 

L'errore:

Exception in thread "main" java.lang.NumberFormatException: For input string: "23e90b831b74" 
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) 
    at java.lang.Integer.parseInt(Integer.java:495) 

risposta

13

23e90b831b74 è troppo grande per rientrare in uno int.

Puoi facilmente vederlo contando le cifre. Ogni due cifre in un numero esadecimale richiede un singolo byte, quindi 12 cifre richiedono 6 byte, mentre un int ha solo 4 byte.

Utilizzare Long.parseLong.

String hexValue = "23e90b831b74";  
long l = Long.parseLong(hexValue, 16); 
3

Ciò si verifica quando "la stringa non può essere analizzata come numero intero". Tra gli altri motivi, ciò si verifica se il valore supera Integer.MAX_VALUE o Integer.MIN_VALUE.

Il numero più grande analizzabile come int è 2147483647 (231-1) e il più lungo è 9223372036854775807 (263-1), solo il doppio del tempo. Per analizzare numeri arbitrariamente lunghi, utilizzare BigInteger:

import java.math.BigInteger; 
BigInteger number = new BigInteger(hexValue); 
Problemi correlati