How do I convert between big-endian and little-endian values in C++?

前端 未结 30 2957
难免孤独
难免孤独 2020-11-21 23:18

How do I convert between big-endian and little-endian values in C++?

EDIT: For clarity, I have to translate binary data (double-precision floating point values and 3

30条回答
  •  野性不改
    2020-11-22 00:18

    On most POSIX systems (through it's not in the POSIX standard) there is the endian.h, which can be used to determine what encoding your system uses. From there it's something like this:

    unsigned int change_endian(unsigned int x)
    {
        unsigned char *ptr = (unsigned char *)&x;
        return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
    }
    

    This swaps the order (from big endian to little endian):

    If you have the number 0xDEADBEEF (on a little endian system stored as 0xEFBEADDE), ptr[0] will be 0xEF, ptr[1] is 0xBE, etc.

    But if you want to use it for networking, then htons, htonl and htonll (and their inverses ntohs, ntohl and ntohll) will be helpful for converting from host order to network order.

提交回复
热议问题