#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
#define CPU_VENDOR_OS "sparc64-unknown-freebsd5.1"
int main(int argc, char* argv[])
{
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
printf("%s \n", CPU_VENDOR_OS);
if(sizeof(short) == 2) {
if(un.c[0] == 1 && un.c[1] == 2)
cout<<"big-endian"<<endl;
else if(un.c[0] == 2 && un.c[1] == 1)
cout<<"little-endian"<<endl;
else
cout<<"unknow"<<endl;
} else {
cout<<"sizeof(short) = "<<sizeof(short)<<endl;
}
return 1;
}
输出结果:
union 联合, 一种特殊的类, 数据共享同一段内存, 以达到节省空间的目的.
举例:
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
using namespace std;
#define CPU_VENDOR_OS "sparc64-unknown-freebsd5.1"
int main(int argc, char* argv[])
{
union {
int i;
struct {
char first;
char second;
} half;
} un;
un.i = 0x4241;
cout<<hex<<un.i<<endl;
cout<<hex<<(int)un.half.first<<" "<<(int)un.half.second<<endl;
un.half.first = 'a';
un.half.second = 'b';
cout<<hex<<un.i<<endl;
return 1;
}
输出结果: