网络编程中,字节顺序是个很重要的东东, 搞不明白, 在异构计算机之间通信很容易出问题。所谓字节顺就是某种数据类型内部字节的顺序,学习过x86汇编应该都知道这么一点,“低位存储在低字节,高位存储在高字节”,这就是所谓的little_endian,相反的叫big_endian,但是要注意的是不要把所有的机器都想象成x86体系结构的little_endian存储,要考虑到程序的通用性和可移植性。下面一段小代码可以判断机器的字节顺序
#include<stdio.h> #define is_little_endian3(x) *(char *)&x union endian_un { short var; char bits[sizeof(short)]; }; int is_little_endian1() { union endian_un flag; flag.var=0x0102; if(flag.bits[0]==1&&flag.bits[1]==2) return 0; else return 1; } int is_little_endian2() { unsigned short flag=0x4321; if(*(char *)&flag==0x21) return 1; else return 0; }
int main() {
if(is_little_endian1()) printf("judge by method 1,little-endian\n"); else printf("judge by method 1,big-endian\n"); if(is_little_endian2()) printf("judge by method 2,little-endian\n"); else printf("judge by method 2,big-endian\n"); short a=0x00ff; if(is_little_endian3(a)) printf("judge by method 3,little-endian\n"); else printf("judge by method 3,big-endian\n");
return 0; }
|
阅读(1184) | 评论(0) | 转发(0) |