htonl() vs __builtin_bswap32()

前端 未结 3 1949
我寻月下人不归
我寻月下人不归 2021-02-10 04:16

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

htonl() is used to reverse bytes too (conver

3条回答
  •  清酒与你
    2021-02-10 04:58

    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.

提交回复
热议问题