C Endianness Conversion with Unions

In C language, endian conversion can be achieved using unions. Here is an example:

#include <stdio.h>

typedef union {
    int value;
    struct {
        unsigned char byte1;
        unsigned char byte2;
        unsigned char byte3;
        unsigned char byte4;
    } bytes;
} EndianConverter;

int main() {
    EndianConverter ec;
    ec.value = 0x12345678;

    printf("Original value: 0x%X\n", ec.value);
    printf("Bytes in memory: 0x%X 0x%X 0x%X 0x%X\n", ec.bytes.byte1, ec.bytes.byte2, ec.bytes.byte3, ec.bytes.byte4);

    // Convert to little endian
    int little_endian = (ec.bytes.byte1 << 24) | (ec.bytes.byte2 << 16) | (ec.bytes.byte3 << 8) | ec.bytes.byte4;

    printf("Little endian value: 0x%X\n", little_endian);

    return 0;
}

In this example, we use a union called EndianConverter to associate an integer value with its four-byte representation. By manipulating the bytes member, we can access each byte of the integer and convert it to little-endian format.

bannerAds