Float to Bytes Type Punning

#include <iostream>
#include <iomanip>
#include <cstdint>
using namespace std;

// Define a union with float f and uint8_t bytes[4]

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;
}

Solving Approach

 

 

 

 

Upvote
Downvote
Loading...

Input

1

Expected Output

00 00 80 3F