Why do both `htons` and `ntohs` exist?

安稳与你 提交于 2021-02-20 10:11:14

问题


I am not sure why htons and ntohs both exist in the standard library. They do exactly the same thing -- unless I'm confused somehow!

The same goes for htonl and ntohl.


回答1:


They make for self-documenting code that tells the reader whether the data is in host- or network- order.




回答2:


This is in case a machine has some sort of unusual endianness besides big-endian or little-endian that isn't one or more simple byte swaps.

For example, if the value 0x0A0B0C0D was represented internally as 0B 0C 0D 0A, then passing this representation to htonl would return 0x0A0B0C0D but ntohl would return 0x0C0D0A0B.

I'm not aware of any platforms that have such a representation, but the presence of separate functions for host-to-network and network-to-host allows for the possibility.



来源:https://stackoverflow.com/questions/37598463/why-do-both-htons-and-ntohs-exist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!