65. Transmit Float as Byte Stream Using Union

#include <stdio.h>
#include <stdint.h>

typedef union {
    float f;
    uint8_t bytes[4];
} FloatPacket;

int main() {
    float input;
    scanf("%f", &input);

    FloatPacket packet;
    packet.f = input;

    for (int i = 0; i < 4; i++) {
        printf("Byte %d: %u", i, packet.bytes[i]);
        if(i < 3){
           printf("\n"); 
        }
    }

    return 0;
}

Explanation

This simulates sending a float value over a byte-wise interface like UART or SPI, where you send each byte one at a time.

Why it’s important in firmware?

  • Many MCUs don’t have hardware float support — floats are handled via byte access
  • Ensures compatibility when sending float over serial
  • Helps with debugging binary protocols

Solution Logic

  • union allows direct access to float’s underlying bytes
  • Array provides raw byte-by-byte transmission
  • Maintains memory alignment automatically
     
Loading...

Input

1

Expected Output

Byte 0: 0 Byte 1: 0 Byte 2: 128 Byte 3: 63