htonl() vs __builtin_bswap32()

21,076

Solution 1

Just look at source code : (example from glib 2.18)

#undef htonl
#undef ntohl

uint32_t
htonl (x)
uint32_t x;
{
    #if BYTE_ORDER == BIG_ENDIAN
       return x;
    #elif BYTE_ORDER == LITTLE_ENDIAN
       return __bswap_32 (x);
    #else
       # error "What kind of system is this?"
    #endif
}
weak_alias (htonl, ntohl)

And : #define __bswap_32(x) ((unsigned int)__builtin_bswap32(x))

Source here : http://fossies.org/dox/glibc-2.18/htonl_8c_source.html

As you can see, htonl only call __builtin_bswap32 on little-endian machines.

Solution 2

I disagree with your statement that htonl() is used to reverse byte order. It is used to convert from host to network byte order. Depending on the byte order of the host, that may, or may not, result in byte order being reversed.

I suggest that you use the function that expresses the correct semantic intent:

  • If you wish to convert from host to network byte order, use htonl().
  • If you wish to reverse byte order, use __builtin_bswap32().

Solution 3

bswap_32 always reverse byte order, on any architecture.

htonl/ntohl reverses byteorder on little endian machines only.

For example, on PowerPC (big endian), ntohl/htonl just returns input value, no more, while bswap32 anyway will reverse byte order.

Share:
21,076
MOHAMED
Author by

MOHAMED

Contact me on LinkedIn.

Updated on February 04, 2020

Comments

  • MOHAMED
    MOHAMED over 4 years

    __builtin_bswap32() is used to reverse bytes (it's used for littel/big endian issues (from gcc)).

    htonl() is used to reverse bytes too (conversion from host to network).

    I checked both functions and they returns the same result.

    Are there some one who can confirm that both functions do the same thing? (standard refences are appreciated)

  • MOHAMED
    MOHAMED over 10 years
    So they are the same if the architecture is little endian
  • MOHAMED
    MOHAMED over 10 years
    So they are the same if the architecture is little endian
  • David Heffernan
    David Heffernan over 10 years
    @MOHAMED Correct. But on a big endian machine, the compiler will turn hotonl() into a simple return input.
  • David Heffernan
    David Heffernan over 10 years
    There's no need to read the source to find this out, and remember that if you just rely on source you might miss an important detail.