53. Modify Bytes in a 32-bit Value Using Union

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

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

void modify_and_print(uint32_t input, uint8_t b1, uint8_t b2) {
    Register reg;
    reg.value = input;

    // Modify byte 1 and 2 (little endian: bytes[1] and bytes[2])
    reg.bytes[1] = b1;
    reg.bytes[2] = b2;

    printf("%u", reg.value);
}

int main() {
    uint32_t num;
    uint8_t b1, b2;
    scanf("%u %hhu %hhu", &num, &b1, &b2);
    modify_and_print(num, b1, b2);
    return 0;
}

This problem demonstrates byte-level mutation of a 32-bit register using union. This is common in hardware register configuration where only certain bytes need to be changed (e.g., setting baud rate, command fields).

Solution Logic:

  • Assign input to .value
  • Modify bytes[1] and bytes[2]
  • Print back the updated value
     
Loading...

Input

305419896 170 187

Expected Output

314288760