Alex Rivera | Logout

How to convert big endian to little endian in C without using library functions?

Asked 2010-02-02T05:09:49.747
120

I need to write a function to convert a big endian integer to a little endian integer in C. I cannot use any library function. How would I do this?

Edit
Report

3 Answers

20

Here's a fairly generic version; I haven't compiled it, so there are probably typos, but you should get the idea,

void SwapBytes(void *pv, size_t n)
{
    assert(n > 0);

    char *p = pv;
    size_t lo, hi;
    for(lo=0, hi=n-1; hi>lo; lo++, hi--)
    {
        char tmp=p[lo];
        p[lo] = p[hi];
        p[hi] = tmp;
    }
}
#define SWAP(x) SwapBytes(&x, sizeof(x));

NB: This is not optimised for speed or space. It is intended to be clear (easy to debug) and portable.

Update 2018-04-04 Added the assert() to trap the invalid case of n == 0, as spotted by commenter @chux.

answered 2010-02-02T08:02:17.420
5

here's a way using the SSSE3 instruction pshufb using its Intel intrinsic, assuming you have a multiple of 4 ints:

unsigned int *bswap(unsigned int *destination, unsigned int *source, int length) {
    int i;
    __m128i mask = _mm_set_epi8(12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3);
    for (i = 0; i < length; i += 4) {
        _mm_storeu_si128((__m128i *)&destination[i],
        _mm_shuffle_epi8(_mm_loadu_si128((__m128i *)&source[i]), mask));
    }
    return destination;
}
answered 2013-07-07T05:44:19.640
-8

If the system is big endian:

For 16 bit values:

unsigned short big = value;
unsigned short little = ((big & 0xFF) << 8) | (big >> 8);

For 32 bit values:

unsigned int big = value;
unsigned int little = ((big & 0xFF) << 24)
                    | ((big & 0xFF00) << 8)
                    | ((big >> 8) & 0xFF00)
                    | (big >> 24);

This isn't the most efficient solution unless the compiler recognizes that this is byte level manipulation and generates byte swapping code. But it doesn't depend on any memory layout tricks and can be turned into a macro pretty easily.

answered 2010-02-02T06:05:00.353

Your Answer