All submissions

Union Extract Bytes from a 32-bit Value

Code

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

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

// Write logic here to extract bytes using union
void print_bytes(uint32_t input) {

    // Initialize a variable of type Register
    Register reg;

    // Assign the 32-bit input value to the 'value' member of the union
    reg.value = input;

    // Print 4 individual bytes in little-endian order
    // In little-endian, the least significant byte LSB is stored first
    // The union allows us to access the same memory as both uint32_t and as 4 bytes
    for(int i = 0; i < 4; i++){
        printf("%d ", reg.bytes[i]);
    }
}

int main() {
    uint32_t num;
    scanf("%u", &num);
    print_bytes(num);
    return 0;
}

Solving Approach

 

 

 

Loading...

Input

305419896

Expected Output

120 86 52 18