看如下代码:
#include <stdio.h>
int main(void)
{
int i = 0x12345678;
int y = 0;
//先看看各种数据类型的大小
printf("sizeof int = %d \n", sizeof(int));
printf("sizeof short int = %d \n", sizeof(short int));
printf("sizeof long int = %d \n", sizeof(long int));
printf("sizeof long long = %d \n", sizeof(long long));
printf("x = 0x%x.\n", i);
//接着就是各个操作的结果
y = htons(i);
printf("y = htons(i) = 0x%x .\n", y);
y = htonl(i);
printf("y = htonl(i) = 0x%x.\n", y);
y = ntohs(i);
printf("y = ntohs(i) = 0x%x.\n", y);
y = ntohl(i);
printf("y = ntohl(i) = 0x%x.\n", y);
return 0;
}
运行结果如下:
./a.out
sizeof int = 4
sizeof short int = 2
sizeof long int = 4
sizeof long long = 8
x = 0x12345678.
y = htons(i) = 0x7856 .
y = htonl(i) = 0x78563412.
y = ntohs(i) = 0x7856.
y = ntohl(i) = 0x78563412.