Little Endian to Big Endian

Code

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

uint32_t convert_endian(uint32_t value) {
    // Write logic to swap bytes

    const size_t BYTE_SIZE = 8; 
    const size_t INPUT_SIZE = 32;

    uint32_t mask_byte_0 = 0x000000FF; // LSB mask
    uint32_t mask_byte_1 = 0x0000FF00;
    uint32_t mask_byte_2 = 0x00FF0000; 
    uint32_t mask_byte_3 = 0xFF000000; 

    uint32_t res = 0; 

    // shift 0th byte
    res |= (value & mask_byte_0) << (INPUT_SIZE - BYTE_SIZE);

    // shift 1st byte
    res |= (value & mask_byte_1) << BYTE_SIZE;

    // shift 2nd byte
    res |= (value & mask_byte_2) >> BYTE_SIZE;

    // shift 3rd byte
    res |= (value & mask_byte_3) >> (INPUT_SIZE - BYTE_SIZE);

    return res;
}

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