How to convert from IEEE Python float to Microsoft Basic float

喜夏-厌秋 提交于 2019-12-05 20:20:02

If you're going to perform these conversions while running under Windows, faster might be to download and install mbf2ieee.exe and call the CVS function offered by the resulting Mbf2ieee.dll (e.g. via [ctypes][2]).

If you're keen to do it in pure Python, I think (but I can't test, having no MBF numbers at hand) that the following might work (I just ported it to Python from C code here):

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]

If this has problems, can you give some examples of input values and expected results?

Edit: if it's the reverse function you want, it should be:

def float2mbf4byte(f):
  ieee = struct.pack('f', f)
  msbin = [0] * 4
  sign = ieee[3] & 0x80

  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
Ilya Murav'jov

Well, I tried float2mbf4byte() and made 2 modifications:

  1. converting negative values is now working,
  2. for Python 2, ieee should be list of int's, not string

The snippet:

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))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!