There are two ways to determine the size of the machine

  • 2020-04-01 21:32:50
  • OfStack

The first way


Idea: use Pointers to cast


#include <stdio.h> 
int main(void)
{    
int data1 = 0x12345678;   
int i;   
for(i=0; i<4; i++)  
{       
printf("%#x ----->%pn",*((char *)&data1 + i),(char *)&data1 + i);   
}     
return 0;
}

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201303/201333143901454.png" >

From the output results, it can be seen that the high address 0xbfc1b1ff stores the high address 0x12 of the data, and the low address 0xbfc1b1fc stores the low address 0x78 of the data. So it's a small end. At the same time, we can also see that the address of the data actually points to the space where the low data is stored.

The second way

Idea: all data is stored from the same address.


#include <stdio.h>
int main(void)
{
    int i;
    union endian
    {
        int data;
        char ch;
    }test;
    test.data = 0x12345678;
    if(test.ch == 0x78)
    {
        printf("little endian!n");
    }
    else
    {
        printf("big endian!n");
    }
 
    for(i=0; i<4; i++)
    {
        printf("%#x ------- %pn",*((char *)&test.data + i),(char *)&test.data + i); 
    }
    return 0;
}

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201303/201333144511215.png" >


Related articles: