UNIX网络编程练习-大小端判断

#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;
}

输出结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值