大端 小端

来源:互联网 发布:phpcms源码 编辑:程序博客网 时间:2024/06/16 13:44

大端模式:指数据的高字节保存在内存的低地址

小端模式:指数据的高字节保存在内存的高地址

测试大小端

方法一:
#include<stdio.h>
int main(int argc, char *argv[])
{
    int i = 0x12345678;
    char c = i;
   if(c==0x78)
    {
 printf("小端\n");
}
else
{
printf("大端\n");
}
    return 0;
}


方法二:

#include<stdio.h>
int main(void)
{
int  a = 0x12345678;
char *p = (char *)&a;
if (0x78 == *p)
{
printf("小端\n");
}
else
{
printf("大端\n");
}
return 0;

}


方法三:

#include<stdio.h>
typedef union NODE
{
int i;
char c;
}Node;
int main(int argc, char *argv[])
{
Node node;
node.i = 0x12345678;
if (0x78 == node.c)
{
printf("小端\n");
}
else
{
printf("大端\n");
}
return 0;
}

这种方式运用到了union(共用体),所谓的共用体,就是共同使用一块内存,共用体的大小是共用体中的所有类型最大的那一个,例如上面的共用体中int是四个字节,char为一个字节,那么这个共用体的大小就是四个字节。先对共用体中的int型数据i赋初值,然后在用char去访问一个字节的数据。


原创粉丝点击