#include <iostream>
#include <iomanip>
#include <cstdint>
using namespace std;
union FloatBytes {
float f;
uint8_t bytes[4];
};
int main() {
float val;
cin >> val;
FloatBytes u;
u.f = val;
cout << hex << uppercase << setfill('0');
for (int i = 0; i < 4; i++) {
cout << setw(2) << static_cast<int>(u.bytes[i]) << " ";
}
return 0;
}
Explanation & Logic Summary:
The union overlays memory so that f and bytes[] occupy the same 4 bytes.
When a value is written to f, the bytes array exposes the raw IEEE-754 binary representation stored in memory.
On little-endian embedded systems:
bytes[0] contains the least-significant bytebytes[3] contains the sign and exponent bitsAlthough this technique is not strictly portable in ISO C++, it is widely used and supported in embedded firmware environments for efficiency and direct memory access.
Firmware Relevance & Real-World Context:
In embedded systems, floating-point sensor values often need to be:
Using a union allows:
This exercise reinforces memory representation awareness, a critical embedded firmware skill.
Input
1
Expected Output
00 00 80 3F