2009-07-02 9 views
6

Wie konvertiert man hexadezimale Zeichenketten in Fließkommazahlen einfacher Genauigkeit in Java?Wie konvertiert man die hexadezimale Zeichenfolge in Float in Java?

Zum Beispiel, wie zu implementieren:

float f = HexStringToFloat ("BF800000"); // f jetzt -1,0

enthalten sollte ich frage das, weil ich versucht habe:

float f = (float)(-1.0); 
String s = String.format("%08x", Float.floatToRawIntBits(f)); 
f = Float.intBitsToFloat(Integer.valueOf(s,16).intValue()); 

Aber ich bekomme die folgende Ausnahme:

java.lang.NumberFormatException: Für die Eingabe-Stichwort: „bf800000 "

Antwort

16
public class Test { 
    public static void main (String[] args) { 

     String myString = "BF800000"; 
     Long i = Long.parseLong(myString, 16); 
     Float f = Float.intBitsToFloat(i.intValue()); 
     System.out.println(f); 
     System.out.println(Integer.toHexString(Float.floatToIntBits(f))); 
    } 
} 
+0

ich: java.lang.NumberFormatException: Für die Eingabe-Stichwort: "BF800000" – apalopohapa

+0

Wenn der Test: Float.intBitsToFloat (Integer.valueOf ("BF800000", 16) .intValue()); Ich bekomme die Ausnahme: java.lang.NumberFormatException: Für Eingabezeichenfolge: "BF800000" – apalopohapa

+0

Es ist ein int überläuft. Wenn Sie es auf Long.valueOf (myString, 16) umstellen, wird die Ausnahme nicht ausgelöst, sondern es wird -1.0 statt 10.0 angezeigt. Sind Sie sicher, dass 10.0 das richtige Ergebnis ist? –

2

Sie müssen den hex-Wert in einen int (links als Übung) konvertieren und dann verwenden Float.intBitsToFloat(int)