Little endian or Big endian

旧城冷巷雨未停 提交于 2020-01-13 19:26:06

问题


#include <stdio.h>

union Endian
{
    int i;
    char c[sizeof(int)];
};

int main(int argc, char *argv[]) 
{
    union Endian e;
    e.i = 1;
    printf("%d \n",&e.i);
    printf("%d,%d,\n",e.c[0],&(e.c[0]));
    printf("%d,%d",e.c[sizeof(int)-1],&(e.c[sizeof(int)-1]));


}

OUTPUT:

1567599464 
1,1567599464,
0,1567599467

LSB is stored in the lower address and MSB is stored in the higher address. Isn't this supposed to be big endian? But my system config shows it as a little endian architecture.


回答1:


You system is definitely little-endian. Had it been big-endian, the following code:

printf("%d,%d,\n",e.c[0],&(e.c[0]));

would print 0 for the first %d instead of 1. In little-endian 1 is stored as

00000001 00000000 00000000 00000000
^ LSB
^Lower Address

but in big-endian it is stored as

00000000 00000000 00000000 00000001
                           ^LSB
                           ^Higher Address  

And don't use the %d to print addresses of variables, use %p.




回答2:


For little endian, the least significant bits are stored in the first byte (with the lowest address).

That's what you're seeing, so it seems there is sanity ;)




回答3:


00000001 (Hexadecimal: 32 bits)
^^    ^^
MS    LS
Byte  Byte

Least Significant Byte at lowest address => little-endian. The integer is placed into memory, starting from its little-end. Hence the name.

Endianness




回答4:


You have the byte containing "1" (least significant) as first element (e.c[0]) and the byte containing "0" being the second one (e.c[1]). This is litte endian, isn't it?




回答5:


You are wrong about what is Big endian and what is little endian. Read this




回答6:


Looks good to me. "little endian" (aka "the right way" :-) means "lower-order bytes stored first", and that's exactly what your code shows. (BTW, you should use "%p" to print the addresses).



来源:https://stackoverflow.com/questions/16395907/little-endian-or-big-endian

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!