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?
#include <iostream> typedef unsigned char uchar; float bytesToFloat(uchar b0, uchar b1, uchar b2, uchar b3) { float output; *((uchar*)(&output) + 3) = b0; *((uchar*)(&output) + 2) = b1; *((uchar*)(&output) + 1) = b2; *((uchar*)(&output) + 0) = b3; return output; } int main() { std::cout << bytesToFloat(0x3e, 0xaa, 0xaa, 0xab) << std::endl; // 1.0 / 3.0 std::cout << bytesToFloat(0x7f, 0x7f, 0xff, 0xff) << std::endl; // 3.4028234 × 10^38 (max single precision) return 0; }
An int and float usually take up "one-word" in memory. Today, with the shift to 64bit systems this may mean that your word is 64 bits, or 8 bytes, allowing the representation of a huge span of numbers. Or, it could still be a 32bit system meaning each word in memory takes up 4 bytes.
Yes it has 4 bytes only but it is not guaranteed.
The IEEE-754 standard (which all processors that support floating point use to my knowledge) defines a single-precision floating point value as 4-bytes.
You could use a memcpy
(Result)
float f; uchar b[] = {b3, b2, b1, b0}; memcpy(&f, &b, sizeof(f)); return f;
or a union* (Result)
union { float f; uchar b[4]; } u; u.b[3] = b0; u.b[2] = b1; u.b[1] = b2; u.b[0] = b3; return u.f;
But this is no more portable than your code, since there is no guarantee that the platform is little-endian or the float
is using IEEE binary32 or even sizeof(float) == 4
.
(Note*: As explained by @James, it is technically not allowed in the standard (C++ §[class.union]/1) to access the union member u.f
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With