如何在 .NET 中将 IEEE Single 转换为 MBF Single

How to convert IEEE Single to MBF Single in .NET

我需要将 .NET 中的 IEEE Single 转换为旧的 MBF Single。这里有一个类似的post,但它与我需要的相反。

Convert MBF Single and Double to IEEE

我可以使用 VB.NET(首选)或 C# 代码。

我在 https://community.embarcadero.com/index.php/article/technical-articles/162-programming/14799-converting-between-microsoft-binary-and-ieee-forma

看到了一个 Borland C++ 的例子

我把这个例子搞得一团糟(我不懂 C++),在 VB.NET 中得出了以下结论。除了零值外它都有效,所以我添加了一个零值检查。我不知道 C++ 代码是否也得到零错误或者它是否是我的转换。无论如何,它似乎有效。

Function MTIS(value As Single) As Byte()

    Dim msbin(3) As Byte

    If value <> 0 Then ' HACK

        Dim ieee As Byte() = BitConverter.GetBytes(value)

        Dim sign As Byte
        Dim msbin_exp As Byte

        sign = ieee(3) And CByte(&H80)
        msbin_exp = msbin_exp Or ieee(3) << 1
        msbin_exp = msbin_exp Or ieee(2) >> 7

        ' An ieee exponent of 0xfe overflows in MBF
        If msbin_exp = CByte(&HFE) Then
            Throw New OverflowException("An IEEE exponent of 0xFE overflows in MBF.")
        End If

        msbin_exp += CByte(2) ' actually, -127 + 128 + 1
        msbin(3) = msbin_exp
        msbin(2) = msbin(2) Or sign
        msbin(2) = msbin(2) Or (ieee(2) And CByte(&H7F))
        msbin(1) = ieee(1)
        msbin(0) = ieee(0)

    End If

    Return msbin

End Function