integer <-> floating point conversion

Kurt

0
Joined
Feb 14, 2003
Messages
113
Location
Los Angeles
A device I communicate with sends to me two 16bit integers. But these 32 bits actually stand internal for a floating-point value. Is there in VB .NET an easy way to convert 4 bytes to a float and back the other way around?
 
No, this is not what Im looking for. Probably my question is not very clear (and not very obvious). Following example describes what I need.

Suppose I get following two integers from the device I have to communicate with: 16455 and 44564

binary this is
16455 = 0100 0000 0100 0111
44564 = 1010 1110 0001 0100

putting them together
0100 0000 0100 0111 1010 1110 0001 0100
this should be a IEEE 754 - compliant represantation of the single precision value 3.12 !!!

So I look for a function that takes 16455 and 44564 as parameters and returns 3.12 .... and the other way arround, a function that takes 3.12 and returns an integer array with the values 16455 and 44564 in.
 
You can achieve this by creating a structure and using an explicit field layout on it so the memory address used by the three variables youre interested in is shared:

Code:
Imports System
Imports System.Runtime.InteropServices

Namespace Test
    Public Class Test

        <StructLayout(LayoutKind.Explicit)> _
         Private Structure Shorts2Float
            <FieldOffset(0)> _
            Public s1 As UInt16
            <FieldOffset(2)> _
            Public s2 As UInt16
            <FieldOffset(0)> _
            Public f As Single
        End Structure

        Public Shared Sub Main()
            Dim s1 As UInt16 = Convert.ToUInt16(16455)
            Dim s2 As UInt16 = Convert.ToUInt16(44564)
            Dim s2f As Shorts2Float = New Shorts2Float
            s2f.s1 = s1
            s2f.s2 = s2
            Dim f As Single = s2f.f
            Debug.WriteLine("{0}", s2f.f.ToString())
        End Sub
    End Class

End Namespace

Something like that ought to get you started.
 
Thanks a lot divil, this is a very nice and easy solution. I work some months with .NET now, but I never used attributes before. I didnt even know what those "<" and ">" signs where :-\
Have you got some links to articles about atributes, or some other things you can advise me to read?
 
Attributes are great - but I dont know of any articles on them. MSDN probably has some good pages on the concept though.
 
Do you know how to convert a number to a spelling string? For example
string method(int k) should return a string which will be k in spelling? E.g. k=10 then string should be "Ten" and not "10".
k=125 then it should say "hundred and twenty-five" etc.?

-A
http://www.autojobapply.com/
[Send your resume to thousands of job-opennings within minutes! Automate your job hunt!]
 
Back
Top