如何从IEEE Python float到microsoftbasi的转换

2024-04-27 02:54:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了Python的float值,我需要将它转换成microsoftbasicsfloat(MBF)格式。 幸运的是,从互联网上得到了一些相反的代码。在

def fmsbin2ieee(self,bytes):
    """Convert an array of 4 bytes containing Microsoft Binary floating point
    number to IEEE floating point format (which is used by Python)"""
    as_int = struct.unpack("i", bytes)
    if not as_int:
        return 0.0
    man = long(struct.unpack('H', bytes[2:])[0])
    exp = (man & 0xff00) - 0x0200
    if (exp & 0x8000 != man & 0x8000):
        return 1.0
        #raise ValueError('exponent overflow')
    man = man & 0x7f | (man << 8) & 0x8000
    man |= exp >> 1
    bytes2 = bytes[:2]
    bytes2 += chr(man & 255)
    bytes2 += chr((man >> 8) & 255)
    return struct.unpack("f", bytes2)[0]

现在我需要扭转这个过程,但还没有成功。有什么帮助吗。在


Tags: returnifbytesasfloatstructintpoint
2条回答

如果您要在Windows下运行时执行这些转换,那么更快的方法可能是下载并安装mbf2ieee.exe,并调用结果Mbf2ieee.dll提供的CVS函数(例如通过[ctypes][2])。在

如果您热衷于用纯Python实现它,我认为(但是我无法测试,因为手头没有MBF编号),下面的方法可能有用(我只是从C code here将其移植到Python):

def mbf2ieee(mbf_4bytestring):
  msbin = struct.unpack('4B', mbf_4bytestring)
  if msbin[3] == 0: return 0.0

  ieee = [0] * 4
  sign = msbin[2] & 0x80
  ieee_exp = msbin[3] - 2
  ieee[3] = sign | (ieee_exp >> 1)
  ieee[2] = (ieee_exp << 7) | (msbin[2] & 0x7f)
  ieee[:2] = msbin[:2]

  return struct.unpack('f', ieee)[0]

如果这有问题,你能给出一些输入值和预期结果的例子吗?在

编辑:如果这是您想要的反向功能,它应该是:

^{pr2}$

嗯,我尝试了float2mbf4byte()并做了两个修改:

  1. 转换负值现在起作用了
  2. 对于python2,ieee应该是int的列表,而不是string

片段:

def float2mbf4byte(f):
    ieee = [ord(s) for s in struct.pack('f', f)]
    msbin = [0] * 4

    sign = ieee[3] & 0x80
    ieee[3] &= 0x7f

    msbin_exp = (ieee[3] << 1) | (ieee[2] >> 7)
    # how do you want to treat too-large exponents...?
    if msbin_exp == 0xfe: raise OverflowError
    msbin_exp += 2

    msbin[3] = msbin_exp
    msbin[2] = sign | (ieee[2] & 0x7f)
    msbin[:2] = ieee[:2]
    return msbin

def ieee2fmsbin(f):
    return struct.pack('4B', *float2mbf4byte(f))

相关问题 更多 >