Current location - Quotes Website - Team slogan - Query on the use of htonl () function in vc++
Query on the use of htonl () function in vc++
Htonl is to convert local byte order into network byte order.

The so-called network byte order (big tail order) refers to the "high to low, low to high" when a number is stored in memory (that is, the high byte of a number is stored in a low address unit and the low byte is stored in a high address unit). However, a computer's memory may store data in a large or small suffix.

Let me give you an example first:

int a = 0x 4032 14;

int b = ht onl(a);

I debugged this code with VC++6.0 and found that

The value of & ampa is 0x00 12ff44.

Among them, the values of 0x00 12ff44, 0x00 12ff45, 0x00 12ff46 and 0x 0 12ff 47 are respectively: 14, 32, 40 and 00, that is, 0x40.

The value of & ampb is 0x00 12ff40.

Among them, the values of 0x00 12ff40, 0x00 12ff438+0, 0x00 12ff42 and 0x0012ff43 are: 00, 40, 32, 14 in turn.

It can be seen that if a number is stored in the order of small tail, the high-order byte of this number will be completely inverted into a new number after being called by htonl function. This new number is actually stored in the machine in the order of small tail, but compared with the original number, it is equivalent to a big tail order.

0x40 of long type is written as: 0x 00 00 00 40, * * four bytes. After calling htonl, the four bytes are in turn 0x4000000.

Similarly, 0x 00 00 00 40 becomes 0x0000 40, that is, 0x40, after calling htonl.

If I have any questions about my answer, you can call me and we will continue our discussion.