-2

In VB6 I am using

Private Type udt1
    i As Long
End Type
Private Type udt2
    f As Single
End Type

Private Function IntBitsToFloat(ByVal u As Long) As Double

    Dim n1 As udt1
    n1.i = u

    Dim n2 As udt2
    LSet n2 = n1

    IntBitsToFloat = n2.f

End Function

I am trying to find the equivalent in VB.NET but I did not find any.

Does anybody know it? Thank you.

Mike Laren
  • 8,028
  • 17
  • 51
  • 70
tmighty
  • 153
  • 4

1 Answers1

0

I think this one works, based on some test values from Wikipedia:

<StructLayout(LayoutKind.Explicit)>
Structure udt
    <FieldOffset(0)> Dim i As Integer
    <FieldOffset(0)> Dim f As Single
End Structure

Function IntBitsToFloat(ByVal u As Integer) As Single
    Dim x As udt
    x.i = u
    Return x.f
End Function

EDIT

Guess I should have searched first! See this answer for a less hacky version, which in VB.NET would be:

Function IntBitsToFloat(ByVal u As Integer) As Single
    Dim bytes = BitConverter.GetBytes(u)
    Return BitConverter.ToSingle(bytes, 0)
End Function

UPDATE

Looks like the hack with the Structure is significantly faster on my PC - e.g. over 100,000,000 iterations in LINQPad:

#1: 00:00:00.0553656
#2: 00:00:01.2785214
Community
  • 1
  • 1
Mark
  • 8,140
  • 1
  • 14
  • 29