56. Little Endian to Big Endian

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

uint32_t convert_endian(uint32_t value) {
    uint32_t byte0 = (value & 0x000000FF) << 24;
    uint32_t byte1 = (value & 0x0000FF00) << 8;
    uint32_t byte2 = (value & 0x00FF0000) >> 8;
    uint32_t byte3 = (value & 0xFF000000) >> 24;

    return byte0 | byte1 | byte2 | byte3;
}

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

What is Endianness?

Endianness defines the byte order in which multibyte data (e.g., int32_t) is stored in memory.

  • Little-endian: LSB stored at lowest address (common in ARM, x86)
  • Big-endian: MSB stored at lowest address

Why It Matters in Firmware?

When communicating over UART, SPI, CAN, or between MCUs with different endianness, you must manually convert the byte order to match protocol or hardware expectations.

Solution Logic

  • Extract each byte using masks
  • Shift it to the new position
  • Combine using | to form the final result
     
Loading...

Input

305419896

Expected Output

2018915346