Modify Bytes in a 32-bit Value Using Union

Code

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

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

// Write logic here using union to modify byte[1] and byte[2]
void modify_and_print(uint32_t input, uint8_t b1, uint8_t b2) {
    // Your logic here
    Register reg;
    reg.value = input;
    //reg.bytes[0] = (input & 0xFF);
    // reg.value &= ~(0xFF << 8);
    // reg.value |= ((b1 & 0xFF) << 8);
    // reg.value &= ~(0xFF << 16);
    // reg.value|= ((b2 & 0xFF) << 16);
    reg.bytes[1] = b1;
    reg.bytes[2] = b2;
    //reg.bytes[3] = ((input & 0xFF000000) >> 24);

    
    //reg.value = (reg.bytes[3] << 24) | (reg.bytes[2] << 16) | (reg.bytes[1] << 8) | (reg.bytes[0]);
    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;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

305419896 170 187

Expected Output

314288760