Big-endian 或 Little-endian 对结构成员的影响是什么?

what is the effect of Big-endian or Little-endian on the members of structure?

给出以下代码片段:

#include <stdio.h>
#include<string.h>
union xyz
{

    int j;
    char b[2];
}y;


int main(void)
{

    y.j=520;
    printf("%d %d",y.b[0],y.b[1]);
    y.b[0]=2;
    printf(" %d ",y.j);
    return 0;

}

对于这段代码,我不知道系统是小端还是大端,如果 y.j 是 520 那么我们的表示是:

0000001000000100 , so y.b[0] should be 2 and y.b[1] should be 4 ,but I am getting y.b[0] as 4 and y.b[1] as 2 ,and my machine is little-endian ,but I am not getting how is the architecture affecting the representation of y.b[0] and y.b[1] ?

在我看来,每当我们创建数组时,都没有像数组的最高有效字节和数组的最低有效字节这样的东西,我们有 b[0] 、 b[1] 、 b[2] 等索引,那么体系结构如何影响数组的表示?

请说明。

你的机器是小端。所以首先存储最低有效字节。对于您的示例,它是 0x08。高字节将为 0x02。

y.b[0] 访问内存中的第一个字节。不是从左到右的第一个字节,因为数字是写在页面上的。所以 y.b[0] 访问 0x08,而 y.b[1] 访问存储在内存中的第二个字节,即 0x02。

如果你的机器是big endian(int是16位的)那么存储在内存中的int的第一个字节是0x02,第二个字节是0x08。因此 y.b[0] 将访问 0x02,而 y.b[1] 将访问存储在内存中的第二个字节,即 0x08.

为了保险起见,还是用short int吧,16位的可能性更大

union xyz {
    short int j;
    char b[2];
} y;

所以在你说完

y.j = 520;

然后 y.j 看起来像这样:

     +-------------+
y.j: |         520 |
     +-------------+

在大端机器上 y.b 看起来像这样:

     +------+------+
y.b: | 0x02 | 0x08 |
     +------+------+
        [0]    [1]

在小端机器上 y.b 看起来像这样:

     +------+------+
y.b: | 0x08 | 0x02 |
     +------+------+
        [0]    [1]