When and how to use C++ htonl function

。_饼干妹妹 提交于 2019-12-06 03:07:07

问题


cout << "Hello World !" << endl;

For my very first post on stackoverflow: When are we supposed to use the htonl function? I have gone through the man page. However, I don't really understand when and how to use it.


回答1:


Host TO Network translation. It makes sure the endian of a 32 bit data value is correct (Big endian) for network transport. ntohl -- Network TO Host -- is used by the receiver to ensure that the endian is correct for the receiver's CPU. Keep an eye out for htons and ntohs for handling 16 bits, and out there somewhere are likely htonll and ntohll for 64 bits.

Using all of them is as simple as pass in the number you want converted and out comes the converted number. You may find that absolutely nothing has happened on some processors because their endian is already big.

uint32_t inval = 0xAABBCCDD;
uint32_t outval = htonl(inval);

Will, on most desktop hardware, result in outval being set to 0xDDCCBBAA



来源:https://stackoverflow.com/questions/30386769/when-and-how-to-use-c-htonl-function

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