1# Utility functions to aid in converting from the special data types the HVIF 2# (aka flat icon format) has 3 4import math 5 6# Example usage: 7# >>> from FlatIconFormat import * 8# >>> read_float_24(0x3ffffd) 9def read_float_24(value): 10 sign = (-1) ** ((value & 0x800000) >> 23) 11 exponent = 2 ** (((value & 0x7e0000) >> 17) - 32) 12 mantissa = (value & 0x01ffff) * 2 ** -17 13 return sign * exponent * (1 + mantissa) 14 15# Example usage: 16# >>> hex(write_float_24(0.9999885559082031)) 17# 18# Does not perform bounds checking. Do not input numbers that are too large. 19def write_float_24(value): 20 # TODO: does not differentiate between 0.0 and -0.0 21 if value >= 0: 22 sign = 0 23 else: 24 sign = 1 25 26 if value != 0: 27 # TODO: make sure exponent fits in 6 bits 28 exponent = math.floor(math.log2(abs(value))) 29 else: 30 exponent = -32 31 32 if value != 0: 33 mantissa = abs(value) / 2**exponent - 1 34 else: 35 mantissa = 0 36 37 return (sign << 23) + ((exponent+32) << 17) + math.floor(mantissa * 2 ** 17) 38