当指数达到-127时如何计算python中的尾数

How to calculate mantissa in python when exponent hit to -127

我有一个十六进制字符串的位置信息。我需要通过 IEEE-754 协议将其转换为浮点整数。

所以我写了这段代码来找到数字的符号,计算指数尾数 来自给定十六进制数的二进制表示。

def _calculte_mantissa(bin_number):
    val = 1
    bit_count = -1
    bit_length = 0
    while bit_length <= 22:
        print bit_count, bit_length
        val += int(bin_number[bit_length]) * 2**bit_count
        bit_count -= 1
        bit_length += 1
        print val
    return val

def convert_position(pos):
    bin_pos = format(int(pos, 16), "0>32b")
    sign = (-1)**int(bin_pos[0], 2)
    exponent = int(bin_pos[1:9], 2) - 127
    mantissa = _calculte_mantissa(bin_pos[9:])
    position = sign * 2**exponent * mantissa
    return position

问题是;如果exponent小于-126,比如-127,结果不正确。我检查结果 from this address,符号和指数结果正确,但尾数结果与我的不同。

我遗漏了该页面所说的内容:

As a result, the mantissa has a value between 1.0 and 2. If the exponent reaches -127 (binary 00000000), the leading 1 is no longer used to enable gradual underflow.

反正我知道问题出在这里,但是我的英文水平不够搞不懂

根据@Rudy Velthuis的建议,我发现如果指数达到-127,我需要删除 1.0 并使用指数 -126 进行计算。所以结果是:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys


def _calculte_mantissa(bin_number, exponent):
    val = 1 if exponent > -127 else 0
    bit_count = -1
    bit_length = 0
    while bit_length <= 22:
        val += int(bin_number\[bit_length\]) * 2**bit_count
        bit_count -= 1
        bit_length += 1
    return val


def convert_ieee754(hex_val):
    bin_pos = format(int(hex_val, 16), "0>32b")
    sign = (-1)**int(bin_pos\[0\], 2)
    _exponent = int(bin_pos\[1:9\], 2) - 127
    mantissa = _calculte_mantissa(bin_pos\[9:\], _exponent)
    exponent = _exponent if _exponent > -127 else -126
    position = sign * 2**exponent * mantissa
    return "Bin: %s - Sign: %s - Exponent: %s (%s) - Mantissa: %s - Posititon: %s" % (bin_pos, sign, exponent,
                                                                                      _exponent, mantissa, position)


if __name__ == "__main__":
    argvs = sys.argv
    print convert_ieee754(argvs\[1\])
    sys.exit()

https://github.com/RecNes/Python-IEEE754-Calculator-with-Denormalized-Values/blob/master/ieee754.py

这个方法对我有用,我从你的脚本中得到的输出始终相同:

import struct
def ieee754(value):
    packed_v = struct.pack('>l', value)
    return struct.unpack('>f', packed_v)[0]

>>> ieee754(0x436be878)
235.9080810546875