how to convert a bit pattern stored in 2 ushorts to a float

G

Guest

I am reading values from a device through a TCP/IP socket that represent an
ANSI float value. However, the values come across as 2 elements in a ushort
array. I need to map the 2 values bit patterns into a floating point number
to get the actual float values being returned.

In C++ I'd finagle it using pointers since a pointer is analogous to an
array. I could just create a ushort pointer, give it the address of a float
variable and assign the values to the pointer using array notation. The float
variable would then have the proper bit pattern.

I don't know how to do that type of thing in C#. Anyone out there know how?

Thanks,

Mike
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

flyfisher1952 said:
I am reading values from a device through a TCP/IP socket that represent an
ANSI float value. However, the values come across as 2 elements in a
ushort
array. I need to map the 2 values bit patterns into a floating point
number
to get the actual float values being returned.

In C++ I'd finagle it using pointers since a pointer is analogous to an
array. I could just create a ushort pointer, give it the address of a
float
variable and assign the values to the pointer using array notation. The
float
variable would then have the proper bit pattern.

I don't know how to do that type of thing in C#. Anyone out there know
how?

Take a look at BitConverter class
 
G

Guest

Here is the solution using BitConverter.

byte[] bytes = new byte[4];
byte[] highBytes = BitConverter.GetBytes(u1);
byte[] lowBytes = BitConverter.GetBytes(u2);

// The order is funky (little endian), but that's intel for you.
bytes[0] = lowBytes[0];
bytes[1] = lowBytes[1];
bytes[2] = highBytes[0];
bytes[3] = highBytes[1];

float fValue = BitConverter.ToSingle(bytes, 0);

return fValue;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top