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 byte_temp;
    uint8_t byte1 = (value >> 0)&0xff;
    uint8_t byte2 = (value>>8)&0xff;
    uint8_t byte3 = (value >>16)&0xff;
    uint8_t byte4 = (value>>24)&0xff;

    //swap byte1  with byte 4 
    byte_temp =byte1;
    byte1 = byte4;
    byte4 = byte_temp;


    // swap byte2 with byte3
    byte_temp = byte2;
    byte2 = byte3;
    byte3 =  byte_temp;

    value &= ~(0xff << 0);
    value |= ((byte1&0xff)<<0);

    value &= ~(0xff << 8);
    value |= ((byte2&0xff)<<8);

    value &= ~(0xff << 16);
    value |= ((byte3&0xff)<<16);

    value &= ~(0xff << 24);
    value |= ((byte4&0xff)<<24);

    return value;
}

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