59. 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) << (int)u.bytes[i] << " ";
    }
    return 0;
}


Solution Details

  • The union overlays memory: f and bytes[4] share the same memory space.
  • Writing to f makes bytes[] reflect the binary IEEE-754 layout.
  • On little-endian systems (common in embedded MCUs):
    • bytes[0] holds the least-significant byte of the float.
    • bytes[3] holds the most-significant byte (sign/exponent).
  • The output may vary across compilers/architectures, but the representation is consistent within a platform.
     

👉 In simple words: The union lets us “peek under the hood” of a float and see its raw bytes.

 

Significance for Embedded Developers

  • Often sensor data (temperature, pressure, etc.) must be sent over UART/SPI/I²C as bytes.
     
  • The union provides a fast, direct way to reinterpret the float without conversions or casting.
     
  • This ensures efficient, low-level control of how data is transmitted.
Loading...

Input

1

Expected Output

00 00 80 3F