Little vs Big Endianess: How to interpret the test

前端 未结 6 964
长发绾君心
长发绾君心 2020-12-11 03:44

So I\'m writing a program to test the endianess of a machine and print it. I understand the difference between little and big endian, however, from what I\'ve found online,

6条回答
  •  半阙折子戏
    2020-12-11 03:54

    int x;
    

    x is a variable which can hold a 32-bit value.

    int x = 1;
    

    A given hardware can store the value 1 as a 32-bit value in one of the following format.

    Little Endian
    0x100    0x101    0x102    0x103
    00000001 00000000 00000000 00000000 
    
    (or) 
    
    Big Endian
    0x100    0x101    0x102    0x103
    00000000 00000000 00000000 00000001
    

    Now lets try to break the expression:

    &x 
    

    Get the address of variable x. Say the address of x is 0x100.

    (char *)&x 
    

    &x is an address of an integer variable. (char *)&x converts the address 0x100 from (int *) to (char *).

    *(char *)&x 
    

    de-references the value stored in the (char *) which is nothing but the first byte (from left to right) in the 4-byte (32-bit integer x).

    (*(char *)&x == 1)
    

    If the first byte from left to right stores the value 00000001, then it is little endian. If the 4th byte from left to right stores value 00000001, then it is big endian.

提交回复
热议问题