How to write endian agnostic C/C++ code?

前端 未结 7 845
我在风中等你
我在风中等你 2020-12-08 00:40

I did some googling and couldn\'t find any good article on this question. What should I watch out for when implementing an app that I want to be endian-agnostic?

7条回答
  •  感动是毒
    2020-12-08 01:22

    The only time you have to care about endianness is when you're transferring endian-sensitive binary data (that is, not text) between systems that might not have the same endianness. The normal solution is to use "network byte order" (AKA big-endian) to transfer data, and then swizzle the bytes if necessary on the other end.

    To convert from host to network byte order, use htons(3) and htonl(3). To convert back, use ntohl(3) and ntohs(3). Check out the man page for everything you need to know. For 64-bit data, this question and answer will be helpful.

提交回复
热议问题