1.思维导图
![](https://i-blog.csdnimg.cn/blog_migrate/d1b7adfd144e9b985c67ce048758ad1f.png)
2.指针形式验证大小端存储
#include<myhead.h>
int main(int argc, const char *argv[])
{
int num = 0x12345678;
char* ptr = (char *)#
if(*ptr == 0x12)
{
printf("big endian\n");
}
else if(*ptr == 0x78)
{
printf("little endian\n");
}
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/5774b5feadeabc0a43a2a333ec83b762.png)
3.共用体形式验证大小端存储
#include<myhead.h>
int main(int argc, const char *argv[])
{
union Endian
{
int num;
char ch;
}data;
data.num = 0x12345678;
if(data.ch = 0x12)
{
printf("big endian\n");
}
else if(data.ch == 0x78)
{
printf("little endian\n");
}
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/e9ee2fb978d2735494352f8439139c31.png)
4.主机字节序与网络字节序转换
#include<myhead.h>
int main(int argc, const char *argv[])
{
unsigned int num = 0x12345678;
unsigned short value = 0x1234;
unsigned int num1 = htonl(num);
unsigned short value1 = htons(value);
printf("num1 = %#x\n",num1);
printf("value1 = %#x\n",value1);
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/7479d7c2d8309c52ea8dbd24ac751e08.png)
5.点分十进制
#include<myhead.h>
int main(int argc, const char *argv[])
{
char *ip = "192.126.125.194";
in_addr_t ip_test = inet_addr(ip);
printf("ip_test = %#x\n",ip_test);
printf("对应的主机字节序为:%#x\n",ntohl(ip_test));
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/347f94b1ce4f26d30267e80abf483497.png)
6.手动实现将小端存储的数据转换成大端存储
#include<myhead.h>
int main(int argc, const char *argv[])
{
int num = 0x12345678;
char *ptr = (char*)#
if(*ptr == 0x12)
{
printf("big endian\n");
}
else if(*ptr == 0x78)
{
printf("little endian\n");
}
char *qtr = ptr+3;
while(qtr > ptr)
{
char temp = *ptr;
*ptr = *qtr;
*qtr = temp;
ptr++;
qtr--;
}
printf("num = %#x\n",num);
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/e6d129ac45ddb8e9f78da304c4057b45.png)