判断字节序的方法有三种,第一种利用联合体来做判断;第二种直接判断大于一个字节的类型最低位的值;第三种利用位域。
1、为啥会有两种字节序
算是历史原因吧,小端序符合cpu的运算习惯,因为cpu也是从低地址和高地址方向读取的;大端符合人类的书写习惯。简单的解释如下:
2、程序判断字节序
#include <iostream> using namespace std; union BigSmall { int dwData; char ucData; }; struct BitSize { char a:4; char b:4; char c:8; }; int main() { //利用联合体 cout<<"fun 1"<<endl; BigSmall tOrder; tOrder.dwData=1; if(1==tOrder.ucData) { cout<<"Small Order"<<endl; } else { cout<<"Big Order"<<endl; } //直接判断int的低位 cout<<"fun 2"<<endl; int dwData=0x12345678; if(*(char *)(&dwData)==0x12) { cout<<"Big Order"<<endl; } else { cout<<"Small Order"<<endl; } //利用位域 cout<<"fun 3"<<endl; BitSize tBit; tBit.a=2; tBit.b=1; tBit.c=0; if(18==*(char *)(&tBit)) { cout<<"Small Order"<<endl; } else { cout<<"Big Order"<<endl; } return 0; }
参考:
https://www.cnblogs.com/zhangxian/articles/3503460.html
https://blog.csdn.net/qq_41757980/article/details/123895547
https://blog.csdn.net/a2998658795/article/details/125829145
标签:判断,字节,int,编程,char,三种,https,article From: https://www.cnblogs.com/JsonZhangAA/p/16897869.html