Hallo,
Ich möchte einen Hexadzimalen String, in ein Float wandeln.
z.b. "40000000" -> 2.0 / "40400000" -> 3.0
Nach IEEE 754.
Dazu findet man sehr viele Ansätze aber ich kann keinen mit dem 
gewünschten Ergebniss finden:
struct.unpack('!f', eingabestring.decode('hex'))[0]
--> String 'str' object has no attribute 'decode'
print(float.fromhex(eingabestring))
--> "40000000" -> 1073741824.0
Vielleich habt ihr eine Idee.
Schöne Grüße,
Matthias
  Matthias schrieb: > Dazu findet man sehr viele Ansätze aber ich kann keinen mit dem > gewünschten Ergebniss finden: Ich kann nicht erkennen, was dein gewünschtes Ergebnis ist. Matthias schrieb: > z.b. "40000000" -> 2.0 / "40400000" -> 3.0 > Nach IEEE 754. Hä?
Ah, jetzt. Mathematische Beispiele mit einem '/' zu trennen ist verwirrend.
1  | struct.unpack("<d", struct.pack("Q",int("0x"+hexString, 16)))[0]
 | 
wer schrieb: > Ah, jetzt. Fast. Der TE wollte single precision:
1  | s = '40400000'  | 
2  | struct.unpack('f', struct.pack('I', int(s, 16)))
 | 
Den Byte-Order-Indikator sollte man in pack und unpack gleich wählen oder beide weglassen.
1  | a="40400000"  | 
2  | |
3  | import binascii  | 
4  | import struct  | 
5  | |
6  | b=binascii.unhexlify(a)  | 
7  | c=struct.unpack(">f", b)
 | 
8  | |
9  | print(c)  | 
Matthias schrieb: > Ich möchte einen Hexadzimalen String, in ein Float wandeln. ABC nach Float? Kann man machen, macht man aber normalerweise nicht. Denn: Float ist ein Datentyp, der "hexstring" eher nicht, nur so ungefähr. Gewandelt wird normalerweise hex nach ASCII oder vom int nach float. Darum: Suchstrategie ineffizent ;) https://stackoverflow.com/questions/33944111/how-to-convert-int-to-float-in-python https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python .. ghci-Beispiel:
1  | [rbx@fe1 ~]$ ghci  | 
2  | GHCi, version 8.6.5: http://www.haskell.org/ghc/ :? for help  | 
3  | Prelude> abc * 1.0  | 
4  | |
5  | <interactive>:1:1: error:  | 
6  | • Variable not in scope: abc  | 
7  | • Perhaps you meant ‘abs’ (imported from Prelude)  | 
8  | Prelude> 'abc' * 1.0  | 
9  | |
10  | <interactive>:2:1: error:  | 
11  | • Syntax error on 'abc'  | 
12  | Perhaps you intended to use TemplateHaskell or TemplateHaskellQuotes  | 
13  | • In the Template Haskell quotation 'abc'  | 
14  | Prelude> 0xabc * 1.0  | 
15  | 2748.0  | 
16  | Prelude>  | 
Andererseits macht der olle Interpreter aber auch ungefragt das hier:
1  | Prelude> 0xa + 0xb  | 
2  | 21  | 
Bitte melde dich an um einen Beitrag zu schreiben. Anmeldung ist kostenlos und dauert nur eine Minute.
  
  Bestehender Account
  
  
  
  Schon ein Account bei Google/GoogleMail? Keine Anmeldung erforderlich!
Mit Google-Account einloggen
Mit Google-Account einloggen
  Noch kein Account? Hier anmelden.