Python - half float 16bit
Z Varhoo
Zajímavý problém jsem nalezl při parsování WAVu a to 16bitový float ( half float popsaný v IEEE 754-2008 )
def HalfToFloat(h):
s = int((h >> 15) & 0x00000001) # sign
e = int((h >> 10) & 0x0000001f) # exponent
f = int(h & 0x000003ff) # fraction
if e == 0:
if f == 0:
return int(s << 31)
else:
while not (f & 0x00000400):
f <<= 1
e -= 1
e += 1
f &= ~0x00000400
print s,e,f
elif e == 31:
if f == 0:
return int((s << 31) | 0x7f800000)
else:
return int((s << 31) | 0x7f800000 | (f << 13))
e = e + (127 -15)
f = f << 13
return int((s << 31) | (e << 23) | f)
data='\x00\x3c'
v = struct.unpack('H', data)
x = HalfToFloat(v[0])
str2 = struct.pack('I',x)
f=struct.unpack('f', str2)