大小端概念
本质上是存储多字节变量时,存储各字节的顺序问题,也就是说单字节变量没有大小端问题
虽然读取变量统一都是从低地址读向高地址,但大小端规定了地址高低与字节高低的关系
如
int32_t a = 0x12345678;
低地址 --> 高地址
12 34 56 78 // 12 是数据的高位,存储在低地址,称为大端(大字节序)存储
78 56 34 12 // 78 是数据的低位,存储在低地址,称为小端(小字节序)存储
判断大小端模式
1.使用内存查看工具直接看电脑的大小端模式
2.编写程序
#include<stdio.h>
#include<stdlib.h>
void test1(){
__int32_t a = 0x12345678;
__int8_t *b = (__int8_t *)&a;
if(*b == 0x12){
printf("大端\n");
}else if(*b == 0x78){
printf("小端\n");
}
printf("%x %x %x %x\n",*b,*(b+1),*(b+2),*(b+3));
}
void test2(){
union
{
__int32_t a;
__int8_t b;
} un;
un.a =0x12345678;
if(un.b == 0x12){
printf("大端\n");
}else if(un.b == 0x78){
printf("小端\n");
}
printf("%x %x %x %x\n",un.b,*(&un.b+1),*(&un.b+2),*(&un.b+3));
}
int main(){
test1();
test2();
return 0;
}
网络通信
统一采用大端模式,即低地址存高位,高地址存低位
如有错误,欢迎指正