Implementation of C Standard Library Function ntohl()
Unless you wish to optimize the code, with specialized swappers for various hosts orders, you are doing it wrong.

I invite you to check The Byte Order Fallacy by Rob Pike. The punch line: the byte order of the computer you are executing the code on doesn't matter, because the language abstracts it for you.

Thus, only the byte order of the network matters, and the network is big-endian:

#include &lt;stdint.h&gt;
#include &lt;string.h&gt;

uint32_t ntohl(uint32_t const net) {
    uint8_t data[4] = {};
    memcpy(&amp;data, &amp;net, sizeof(data));

    return ((uint32_t) data[3] &lt;&lt; 0)
         | ((uint32_t) data[2] &lt;&lt; 8)
         | ((uint32_t) data[1] &lt;&lt; 16)
         | ((uint32_t) data[0] &lt;&lt; 24);
}


This function will work no matter the endianness of the host, even on the crazy middle-endians ones.

Oh, and it optimizes well in general, in case you were wondering:


ntohl(unsigned int):
        mov     eax, edi
        bswap   eax
        ret



bswap being the native CPU instruction to swap bytes on x86.