Reputation: 29
I need to convert an IEEE Single in .NET to the old MBF Single. There is a similar post here but it does the opposite of what I need.
Convert MBF Single and Double to IEEE
I can use either VB.NET (preferred) or C# code.
Upvotes: 0
Views: 128
Reputation: 29
I came across an example in Borland C++ at https://community.embarcadero.com/index.php/article/technical-articles/162-programming/14799-converting-between-microsoft-binary-and-ieee-forma
I muddled through the example (I don't know C++) and came up with the following in VB.NET. It works except for the value of zero so I added a check for zero. I don't know if the C++ code also gets zero wrong or if it's my conversion. Anyway, it seems to work.
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
Upvotes: 0