首页 > 代码库 > Duanxx的嵌入式学习: 大端模式和小端模式

Duanxx的嵌入式学习: 大端模式和小端模式






测试代码:

<span style="font-size:18px;"># 1 
/* program to find machine is little endian  or little endian */
#include<stdio.h>

int main()
{
 int x=0x12345678;
 char *p;
 p=(char *)&x;
 if(*p == 0x78) {
    printf("Little endian \n");
 } else {
   printf("Big endian \n");
 }
return 0;
}

#2
/* another correct way is using unions */
int main()
{ 

union e {
       int x;
       char y;
};


union e p1;
p1.x=0x12345678;

if(p1.y == 0x78) {
    printf("Little endian \n");
 } else {
   printf("Big endian \n");
}
return 0;
}

#3
below is same as #1 with more simplified

shiv@ubuntu:~/ds/misc$ 
/* following is not correct way to find the machine */
 #include<stdio.h>

int main()
{
int num=1;

if(*(char *)&num == 1)
 {
    printf("Little\n");
 } else {
   printf("Big endian\n");
}

}</span>


Duanxx的嵌入式学习: 大端模式和小端模式