159. Float to Bytes Type Punning

#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 byte
  • bytes[3] contains the sign and exponent bits

Although 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:

  • Serialized for UART, SPI, or I²C
  • Packed into network or storage frames
  • Transmitted without conversion overhead

Using a union allows:

  • Zero-copy serialization
  • Predictable memory layout
  • Efficient low-level data handling

This exercise reinforces memory representation awareness, a critical embedded firmware skill.

 

 

 


 

Loading...

Input

1

Expected Output

00 00 80 3F