Search code examples
cendianness

Conversion to little endian format in C


I have an array int16_t arr[4]; . What I want to do is to convert a value in this array to little endian. For example, let us say I have 0x1d02 on the first index, but I need 0x21d there. Is there any elegant way of converting that and writing it back to the array or how are these things done? Note that I just expressed myself in hex, because its easier to see the problem.


Solution

  • #define BS16(x) (((x) >> 8) | ((x) << 8))
    
    int main(void)
    {
        uint16_t arr[] = {0x1122, 0x2233, 0xaabb};
        printf("%hx %hx %hx\n", BS16(arr[0]), BS16(arr[1]), BS16(arr[2]));
        arr[0] = BS16(arr[0]);
    }