C程序检查与小大端 [英] C program to check little vs. big endian
问题描述
可能重复:结果
<一href=\"http://stackoverflow.com/questions/2100331/c-macro-definition-to-determine-big-endian-or-little-endian-machine\">C宏定义确定big endian还是little endian机器?
块引用>INT的main()
{
INT X = 1; 字符* Y =(字符*)及X; 的printf(%C \\ n,* Y + 48);
}如果是小尾数将会打印1.如果是大尾数将打印0.这是否正确?或将设定一个char *为int点¯x始终指向至少显著位,不管字节序?
解决方案在简而言之,是的。
假设我们有一个32位计算机上。
如果是小端,在
X
中的内存将是这样的:更高的内存
-----&GT;
+ ---- + ---- + ---- + ---- +
| 0×01 | 0×00 | 0×00 | 0×00 |
+ ---- + ---- + ---- + ---- +
一个
|
&安培; X所以
(字符*)(* X)== 1
和* Y + 48 = =1
。如果它是大端,这将是:
+ ---- + ---- + ---- + ---- +
| 0×00 | 0×00 | 0×00 | 0×01 |
+ ---- + ---- + ---- + ---- +
一个
|
&安培; X所以这将是一个
0
。Possible Duplicate:
C Macro definition to determine big endian or little endian machine?
int main() { int x = 1; char *y = (char*)&x; printf("%c\n",*y+48); }
If it's little endian it will print 1. If it's big endian it will print 0. Is that correct? Or will setting a char* to int x always point to the least significant bit, regardless of endianness?
解决方案In short, yes.
Suppose we are on a 32-bit machine.
If it is little endian, the
x
in the memory will be something like:higher memory -----> +----+----+----+----+ |0x01|0x00|0x00|0x00| +----+----+----+----+ A | &x
so
(char*)(*x) == 1
, and*y+48 == '1'
.If it is big endian, it will be:
+----+----+----+----+ |0x00|0x00|0x00|0x01| +----+----+----+----+ A | &x
so this one will be
'0'
.这篇关于C程序检查与小大端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!