How do I convert a 4-byte array (of type bytes) into a 4-byte floating-point?  
Author Message
Furqan Farooqui





PostPosted: Visual C# General, How do I convert a 4-byte array (of type bytes) into a 4-byte floating-point? Top

Okay, how do I convert an array of bytes into the 4-byte floating-point number with the same binary representation

What I'm trying to do is, that when I loaded a binary file into memory, I want to be able to set the four bytes of a byte array to some values, and then retrieve the value in floating-point.

In C++, this would've been rather easy using pointers, as shown :

char buffer[4]; // Set some values to this buffer

float* fp = (float*)buffer; // Access the 4-byte array as a floating point

cout << "Floating point value : " << *fp << endl; // Print it

Now how do I do this without pointers Don't tell me to try to load the floating-points directly from the file, by using some function like ReadDWord.

Any ideas Plz help. Thanks in advance.




Visual C#9  
 
 
Mattias Sjogren





PostPosted: Visual C# General, How do I convert a 4-byte array (of type bytes) into a 4-byte floating-point? Top

You can find one way of doing it in Jon Skeet's MiscUtil library at http://www.yoda.arachsys.com/csharp/miscutil/. Look in the EndianBitConverter class.



 
 
Matthew Watson





PostPosted: Visual C# General, How do I convert a 4-byte array (of type bytes) into a 4-byte floating-point? Top

This is quite simple: Use the BitConverter.ToSingle() method.



 
 
Furqan Farooqui





PostPosted: Visual C# General, How do I convert a 4-byte array (of type bytes) into a 4-byte floating-point? Top

Oh...cool. That was easy. I was looking for the byte to float in the documentation, hence I couldn't find it myself. Now I know they call floats a 'single'. Thanks!


 
 
Furqan Farooqui





PostPosted: Visual C# General, How do I convert a 4-byte array (of type bytes) into a 4-byte floating-point? Top

This looks like a nice utility library. I'll check it out when I need to control the endianess of the bits too.