Little Endian to Big Endian

Using unions

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

union Word{
    uint32_t val;
    uint8_t raw[4];
};

uint32_t convert_endian(uint32_t value) {
    // Write logic to swap bytes
    uint8_t t;
    union Word ele;
    ele.val = value;
    //swapping the no.s
    t = ele.raw[3];
    ele.raw[3] = ele.raw[0];
    ele.raw[0] = t;
    //swapping the no.s
    t = ele.raw[2];
    ele.raw[2] = ele.raw[1];
    ele.raw[1] = t; 

    return ele.val;
}

int main() {
    uint32_t val;
    scanf("%u", &val);
    printf("%u", convert_endian(val));
    return 0;
}

Solving Approach


 

Upvote
Downvote
Loading...

Input

305419896

Expected Output

2018915346