114. Little Endian to Big Endian

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint32_t convert_endian(uint32_t value) {
    // Write logic to swap bytes
    uint32_t conversion = value;
    uint8_t byte_1, byte_2, byte_3, byte_4;
    uint32_t merge_conversion = 0;

    byte_1 = conversion;
    conversion >>= 8;
    byte_2 = conversion;
    conversion >>= 8;
    byte_3 = conversion;
    conversion >>= 8;
    byte_4 = conversion;

    merge_conversion |= byte_1;
    merge_conversion <<= 8;

    merge_conversion |= byte_2;
    merge_conversion <<= 8;

    merge_conversion |= byte_3;
    merge_conversion <<= 8;

    merge_conversion |= byte_4;
    
    return merge_conversion;
}

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

Solving Approach


 

Was this helpful?
Upvote
Downvote