用一个例子演示htons的用法,用于编译的centos虚拟机为小端模式,因此下面的程序输出为
10 00
4096
与htons函数类似的几个函数及对应的作用如下:

uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);
Description
The htonl() function converts the unsigned integer hostlong from host byte order to network byte order.
The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.

The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.

The ntohs() function converts the unsigned short integer netshort from network byte order to host byte order.

On the i386 the host byte order is Least Significant Byte first, whereas the network byte order, as used on the Internet, is Most Significant Byte first.
/*************************************************************************\
*                  Copyright (C) 52coder, 2018.                           
*                                                                         
* 本例演示函数htons,解释数据在底层的存储。主体程序来自于深入理解计算机系统          
* 代码中使用typedef将数据类型byte_pointer定义为一个指向类型为unsigned char的对象的指针,
* 这样一个字节指针引用一个字节序列,其中每个字节都被认为是一个非负整数。
* htons用于将主机字节序转换为网络字节序,该例子能清晰说明转变过程。
\*************************************************************************/

#include <stdio.h>
typedef unsigned char * byte_pointer;
void show_bytes(byte_pointer start,size_t len)
{
    size_t i;
    for(i = 0 ;i < len;i++)
    {
        printf(" %.2x",start[i]);
    }
    printf("\n");
}

void show_short(short x)
{
    show_bytes((byte_pointer)&x,sizeof(x));
}

void show_int(int x)
{
    show_bytes((byte_pointer)&x, sizeof(x));
}

void show_float(int x)
{
    show_bytes((byte_pointer)&x, sizeof(x));
}

void show_pointer(void *x)
{
    show_bytes((byte_pointer)&x, sizeof(x));
}
void test_show_bytes(int val)
{
    int ival = val;
    float fval = (float)ival;
    int *pval = &ival;
    show_short(ival);

}

int main()
{
    short int x = 16;
    test_show_bytes(x);
    printf("%d\n",htons(x));
    return 0;
}