Konvertierung von Python-floats in IEEE754-binaries und vice versa
Einige knappe Python3-Hilfsfunktionen zum Konvertieren von floats in IEEE754-Bin?rzahlen und umgekehrt. Am Ende des Listings finden sich einige Aufrufbeispiele. Für den theoretischen Hintergrund empfiehlt sich ein Besuch bei wikipedia: https://de.wikipedia.org/wiki/IEEE_754
getBin = lambda x: x > 0 and str(bin(x))[2:] or "-" + str(bin(x))[3:]
def floatToBinary32(value):
val = struct.unpack('I', struct.pack('f', value))[0]
return getBin(val)
def floatToBinary64(value):
val = struct.unpack('Q', struct.pack('d', value))[0]
return getBin(val)
def binaryToFloat64(value):
hx = hex(int(value, 2))
return struct.unpack("d", struct.pack("q", int(hx, 16)))[0]
def binaryToFloat32(value):
return struct.unpack("f", struct.pack("I", int(value, 2)))[0]
f = 0.75
i64 = floatToBinary64(f)
i32 = floatToBinary32(f)
print("%f == b64:%s" % (f, i64))
print("%f == b32:%s" % (f, i32))
ff64 = binaryToFloat64(i64)
ff32 = binaryToFloat32(i32)
print("ff64 = %f" % (ff64))
print("ff32 = %f" % (ff32))