32位浮点单精度hex 字符串转 十进制 小数
新增粉尘仪检测设备调试中需要对 hex 32位浮点数 转10 进制小数(保留三位小数)
def ieee_transfer(hex_str): """ :param hex_str: hex string like '4145851F' :return: float type """ ret = '' for i in range(0, len(hex_str), 2): a = hex_str[i: i + 2] intItem = int(a, 16) binary_str = bin(intItem)[2:len(bin(intItem))] binary_str = "%(binary)08d" % {'binary': int(binary_str)} ret = ret + binary_str sign_head = int(ret[0]) exponent = int(ret[1:9], 2) real_num = ret[9:len(ret) - 1] m = float() for i in range(1, len(real_num) - 1, 1): if real_num[i - 1] == "1": m = m + 0.5 ** i val = (-1) ** sign_head * 2 ** (exponent - 127) * (1 + m) return round(val, 3)