Little endian: the low bit of data is stored in the low address
Big endian:
This difference in data storage method is not caused by the operating system, but by the processor architecture.
1 #include
2
3 int main(int argc, char *argv[])
4 {
5 int a = 0x12345678;
6 char *p = (char *)&a;
7 if(*p = 0x78)
8 printf("little endian\n");
9 else
10 fprintf(stdout, "big endian\n");
11
12 return 0;
13 }
1 #include
2
3 /* Data storage form test function, big endian method returns 0, little endian method returns 1 */
4 int test_endian(void)
5 {
6 int a = 0x12345678; // data for testing
7 char *p= (char *)&a; // Pointer converted to character data
8
9 if(*p == 0x78) // judge the order of the lowest byte
10 return 1;
11 return 0;
12}
13
14 int main(int argc, char *argv[])
15 {
16 if(test_endian() == 1) // little endian
17 {
18 /* corresponding operation */
19}
20 else // big endian
twenty one {
22 /* corresponding operation */
twenty three }
24 return 0;
25 }
Verify that the network byte order is big-endian
1 #include
2
3 int main(int argc, char *argv[])
4 {
5 int a = 0x12345678;
6 int b = htonl(a);
7 char *p = (char *)&b;
8 if((int)*p == 0x78)
9 printf("little-endian\n");
10 else if((int)(*p) == 0x12)
11 printf("big-endian\n");
12 else
13 printf("unkonwn\n");
14
15 return 0;
16 }