posted:
I am interested in converting sets of 4 bytes to floats in C++. I have
a library that reads image data and returns the data as an array of
unsigned chars. The image data is stored as 4-byte floats. How can I
convert the sets of 4 bytes to floats?
Thanks,
Greg Book
Here's one method, but the array must be suitably aligned for it to work.
float &Float(char unsigned *const p)
{
return reinterpret_cast<float&>(*p);
}
float const &Float(char unsigned const *const p)
{
return reinterpret_cast<float const&>(*p);
}
void FuncWantsFloat(float) {}
int main()
{
char unsigned arr[sizeof(float)] = {};
FuncWantsFloat( Float(arr) );
}
(Note that no copy is made -- the char array is simple accessed
differently. The float will have the same lifetime as the char array.)
If the char array is NOT suitably aligned, you could always do something
like:
#include <cstring>
using std::memcpy;
float Float(char unsigned *const p)
{
float val;
memcpy(&val,p,sizeof val);
return val;
}
int main()
{
char unsigned arr[4] = {};
Float(arr);
}
--
Frederick Gotham