52. Union Extract Bytes from a 32-bit Value

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

typedef union {
    uint32_t value;
    uint8_t bytes[4];
} Register;

void print_bytes(uint32_t input) {
    Register reg;
    reg.value = input;

    for (int i = 0; i < 4; i++) {
        printf("%u", reg.bytes[i]);
        if(i < 3){
            printf(" ");
        }
    }
}
 
int main() {
    uint32_t num;
    scanf("%u", &num);
    print_bytes(num);
    return 0;
}

Unions allow different types to share the same memory. This is extremely helpful in firmware where byte-wise access to multibyte registers is needed — for UART framing, CRC, SPI/I2C transmission, etc.

Solution Logic:

  • Define a union with uint32_t and uint8_t[4]
  • Assign to the value field
  • Access individual bytes via bytes[] (LSB is bytes[0] in little-endian systems)

 

Loading...

Input

305419896

Expected Output

120 86 52 18