def byte_to_float(b, mantissabits=5, zeroexp=2): """Decodes a floating point number stored in a single byte. """ b = ord(b) if b == 0: return 0.0 bits = (b & 0xff) << (24 - mantissabits) bits += (63 - zeroexp) << 24 return unpack("f", pack("i", bits))[0]
def float_to_byte(value, mantissabits=5, zeroexp=2): """Encodes a floating point number in a single byte. """ # Assume int size == float size fzero = (63 - zeroexp) << mantissabits bits = unpack("i", pack("f", value))[0] smallfloat = bits >> (24 - mantissabits) if smallfloat < fzero: # Map negative numbers and 0 to 0 # Map underflow to next smallest non-zero number if bits <= 0: return chr(0) else: return chr(1) elif smallfloat >= fzero + 0x100: # Map overflow to largest number return chr(255) else: return chr(smallfloat - fzero)