Little Endian to Big Endian

Code

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

uint32_t convert_endian(uint32_t value) {
    // Write logic to swap bytes
    uint8_t *address=(uint8_t *)&value;
    uint32_t ret=0;
    for (uint32_t i=0;i<4;i++){
        ret=(ret<<8)|*(address+i);
    }
    return ret;


    /*
    //SECOND APPROACH

    uint32_t byte0=((value >> 24) & (0x000000ff));
    uint32_t byte1=((value >> 8) & (0x0000ff00));
    uint32_t byte2=((value << 8) & (0x00ff0000));
    uint32_t byte3=((value << 24) & (0xff000000));
    
    return byte0|byte1|byte2|byte3;
    */
}

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