December 12 2006

来源:互联网 发布:php if判断不等于符号 编辑:程序博客网 时间:2024/05/16 07:09

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);

原创粉丝点击