编程判断大端方式还是小端方式
我自己的理解和代码如下:
如果数字0x12345678
那么大端方式从低地址到高地址依次存储 0x12 0x34 0x56 0x78
如果是小端方式的话从低地址到高地址依次存储 0x78 0x56 0x34 0x12
我的程序如下:
int main()
{
unsigned int i=0x12345678;
cout<<hex<<i<<endl;
char *p=(char *)&i;
if(*p==0x78)
cout<<"little Endition"<<endl;
else
cout<<"Big Endition"<<endl;
return 0;
}
结果输出却让我大跌眼镜
12345678
Big Endition
输出我有点看不懂,一般笔记本不都是大端方式吗?
还有一个问题,编程实现大端方式小端方式,我在网上搜了下还有用UNION联合体,没看懂,求解答。联合体不是在同一时刻只能存储一个变量吗,在给c.a赋值后,c.b怎么可能为1呢?
int checkCPU()
{
{
union w
{
int a;
char b;
}c;
c.a = 1;
return (c.b == 1);
}
}
附上个人电脑信息:
MacBook Pro (Retina, 13-inch, Early 2015)
处理器 2.7 GHz Intel Core i5
编辑器 Xcode6
If you don’t understand C++, let’s talk about union. Assume that int is 4 bytes, then when c.a=1 is set, the memory is 0x00000001 in big endian, because the high bits are all 0 and the lowest bit is 01. The memory address from left to right is from low to high, which conforms to the definition of big endian high bits. The byte is in the lower memory address.
The opposite is true for little endian, which is 0x01000000 in memory. b is char, occupies one byte, and is a byte at a low memory address. If it is in little-endian mode, it is 0x01, and in big-endian mode it is 0x00. The conclusion is that if c.b==1 returns true, it is little endian.
Supplement: Intel x86 processors are all little-endian, and most machines now have Intel CPUs.
I understand C++, and the conclusion is correct, it is little-endian.
A consortium is a storage area shared by members of the consortium, and the space used by a is also used by b
Don’t use programming to test
Because you can’t control the compiler behavior
Different compilers produce different machine codes
Because these things are not clearly specified in the C++ and C language specifications
Please check cpu manual this is the only way
I used your program on the x86_64 platform (Intel core i5-4590) and indeed measured little endian.
(I think endian is written wrong...)
I don’t have a MacbookPro to try.
I don’t see anything wrong with your way of writing, I can only say that the result is very strange...
The following is the usage of union.
Union means "the type of this memory data may be one of the following:..."
(The compiler will automatically allocate a section of memory to ensure that it is enough to accommodate the largest type)
So in the question The meaning of union means "the variable c may be either int or char".
And c.a means "treat c as int", and c.b means "treat c as char".
In other words, c.a is equivalent to (int)(&c), and c.b is equivalent to (char)(&c).
So, there is no problem in using c.a first and then c.b. You just operate c as different types at different times.
Then it will be no different from the program you wrote...
Intel processors are indeed little-endian. Who told you that laptops are big-endian?
Just compare char and multi-byte types directly. UNION is feasible, but it is of no use. You will fart when you take off your pants. Things