I\'m trying to build a 32-bit float out of its 4 composite bytes. Is there a better (or more portable) way to do this than with the following method?
#includ
You can use std::copy:
float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3)
{
uchar byte_array[] = { b3, b2, b1, b0 };
float result;
std::copy(reinterpret_cast(&byte_array[0]),
reinterpret_cast(&byte_array[4]),
reinterpret_cast(&result));
return result;
}
This avoids the union hack, which isn't technically allowed by the language. It also avoids the commonly used reinterpret_cast, which violates the strict aliasing rules (it is permitted to reinterpret any object as an array of char, so the reinterpret_casts in this solution do not violate the strict aliasing rules).
It still relies on float being four bytes in width and relies on your four bytes being a valid floating point number in your implementation's floating point format, but you either have to make those assumptions or you have to write special handling code to do the conversion.