December 12 2006

int checkCPU(){
  union w{
   int a;
   char b;
  } c;
  c.a = 1;
  return (c.b == 1);
}

  The above function is in my e-mail from one of my workmates.  He turned to me in that he can not
understand it.  The main task of this function is used to check if a CPU in our PC or other computer
store a big integer in big endian mode or in litte endian mode.

  Because there are more than one CPU factory, they have their instrument sets, architectures, it
is not strange completely that there is a discrepancy of storing.  For example, there a number 0x12345678.
In some architectures, it is stored in following way:

content address
0x78 :0x4000
0x56 :0x4001
0x34 :0x4002
0x12 :0x4003

this way is called "litte endian", or stored in other way:

content address
0x12 :0x4000
0x34 :0x4001
0x56 :0x4002
0x78 :0x4003

it is called "big endian".

  Okey!  Let's come back to the function.  There is a "union" type variable "c".  The "union"
type has a feature, its size come up to the size of its maximum size member.  The "c" has two
members, one is "a", integer, another is "b", char type.  So, the size of "c" is 4 bytes --
32 bits, in that the integer type "a" is also 4 bytes, 32 bits.  The char type "b" is just one
byte, 8 bits.

  There is another important thing.  The begin addresses of all members of a "union" type
variable are same.  So, &c==&c.a==&c.b though their size and type are same incompletely.

  Now we assigned 1 to "c.a".  Do you remember how to express 1 in binary?  Yes, 00000000 00000000
00000000 00000001.  If CPU store 1 in "little endian",

content  address
00000000 :0x1000
00000000 :0x1001
00000000 :0x1002
00000001 :0x1003

the "c.b==1" will get 0 (false); in "big endian",

content  address
00000001 :0x1000
00000000 :0x1001
00000000 :0x1002
00000000 :0x1003

the "c.b==1" will get 1 (true).

  Now you will understand why this function can check CPU storing mode and how to check it.  But
it is not only way to check CPU mode.  The following is another cheque function whose mechanism
is similar to that.

int checkCPU(){
 int a=1;
 char *p=(char*)&a;
 
 return *(p+1);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值