Size-end Mode Conversion Function

Source: Internet
Author: User

The size-end mode conversion functions are htonl (), htons (), ntohl (), and ntons () -- the size-end Mode Conversion Function varies with the byte storage order of variables on different machines, some adopt the big-endian mode, and some adopt the little-endian mode ). The big-end Mode means that the high-byte data is stored at the low address, and the low-byte data is stored at the high address. The small-end Mode means that the low-byte data is stored at the low address, and the high-byte data is stored at the high address. During data transmission over the network, because the two ends of data transmission may correspond to different hardware platforms, the storage byte sequence may be inconsistent, therefore, the TCP/IP protocol specifies that the network must adopt the byte sequence (that is, the large-end mode ). By analyzing the storage principle of the size end, we can find that char data occupies only one byte, so this problem does not exist, this is also one of the reasons for defining the data buffer as a char type. For non-char data such as IP address and port number, it must be converted to the big-end mode before the data is sent to the network, after receiving the data, convert it into a storage mode that complies with the receiver host. In Linux, four functions are provided for big and small-end mode conversion. input the man byteorder command to obtain the function prototype: # include <arpa/inet. h> define htonl (assign hostlong); uint16_t htons (uint16_t hostshort); uint32_t ntohl (assign netlong); Define ntohs (uint16_t netshort); htonl indicates host to network long, it is used to convert host unsigned int type data to the network byte sequence; htons indicates host to network short, used to convert host unsigned short type data to the network byte sequence; ntohl and ntohs functions are opposite to htonl and htons respectively.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.