htonl
converts a "host-order" number to network byte order. Host order is whatever endianness you have on the system running the code. Network byte order is big-endian. If host-to-network is big-to-big, that means no change -- which is what 13
-> 13
would verify. On the other hand, if host-to-network is small-to-big, that means you'll get swapping, so the least-significant byte 13
(least because changing it by 1 changes the overall number only by 1) would become most-significant-byte 13
(most because changing that byte by one changes the overall number by the largest amount), and 13
-> (13 << 24)
.
13
specifically is unimportant. You could use any number, so long as its little-endian representation wasn't the same as its big-endian representation. (0
would be bad, because 0
byte-swapped is still 0
. Same for (65536 + 256)
as well, because the 32-bit representation is 00 01 01 00
in both big-endian and little-endian.
Note that there are also mixed-endian systems where for the 32-bit number 0x12345678
, you'd have bytes not in the order 12 34 56 78
(big-endian) or 78 56 34 12
(little-endian): 34 12 78 56
for one, I believe. These systems aren't common, but they do still exist, and the code here wouldn't handle them correctly.
http://gcc.gnu.org/onlinedocs/gcc-4.2.0/gcc/Other-Builtins.html and http://gcc.gnu.org/onlinedocs/gcc-4.3.0/gcc/Other-Builtins.html suggest __builtin_bswap32
was added in gcc 4.3, so your gcc 4.1.2 toolchain wouldn't have it.