叁:大小端模式(Big_Little_Endian)

2016-06-29  本文已影响52人  恰冯同学年少

1:处理器存储多字节数据时,存在大端和小端模式;
2:处理器存储单字节数据时,位顺序也存在大端和小端模式;
3:小端模式:低地址存储低位的数据(字节),高地址存储高位数据(字节);
4:大端模式:低地址存储高位数据(字节),高地址存储高位数据(字节);


One:使用共同体结构判断多字节存数模式

/********************************
*Function:测试处理器大小端模式
*Platform:X86
*Compiler:GCC
*Author:Programme By Golf
** *****************************/

#include <stdio.h>

typedef union 
{
    unsigned short  Data;
    struct
    {
        unsigned char a[2];
    }cc;
}Big_Little;

Big_Little big_little; 

void main()
{
    char *ptr1 = "Little_Mode"; 
    char *ptr2 = "Big_Mode";
    big_little.Data = 0x11aa;
    if(big_little.cc.a[0] == 0xaa && big_little.cc.a[1] == 0x11)
    {
        printf("big_little.Data = 0x%x\n",big_little.Data);
        printf("addre = %p value = 0x%x\n",&big_little.cc.a[0],big_little.cc.a[0]);
        printf("addre = %p value = 0x%x\n",&big_little.cc.a[1],big_little.cc.a[1]);
        printf("%s\n",ptr1);
    }
    if(big_little.cc.a[1] == 0xaa && big_little.cc.a[0] == 0x11)
    {
        printf("big_little.Data = 0x%x\n",big_little.Data); 
        printf("addre = %p value = 0x%x\n",&big_little.cc.a[0],big_little.cc.a[0]);
        printf("addre = %p value = 0x%x\n",&big_little.cc.a[1],big_little.cc.a[1]);
        printf("%s\n",ptr2);
    }
}

Two:使用共同体结构判断单字节存数模式(位顺序)

/********************************
 * *Function:测试处理器大小端模式
 * *Platform:X86
 * *Compiler:GCC
 * *Author:Programme By Golf
 * ** *****************************/

#include <stdio.h>

typedef union
{
    unsigned char data;
    struct
    {
        unsigned char a:1;
        unsigned char b:1;
        unsigned char c:1;
        unsigned char d:1;
        unsigned char e:1;
        unsigned char f:1;
        unsigned char g:1;
        unsigned char h:1;
    }cc;
}big_little;

big_little Big_Little;

void main()
{
    
    Big_Little.data = 0x01;
    if(Big_Little.cc.a == 0x01)
        printf("Little_MOde\n");
    else
    if(Big_Little.cc.h == 0x01)
        printf("Big_MOde\n");
    else
        printf("error\n");
}

Three:使用指针判断大小端模式

/******************************
*测试处理器大小端模式
*Platform:X86
*Compiler:GCC
*Author:Programme By Golf
*****************************/

#include <stdio.h>

void main(void)
{
    char c1;
    char c2; 
    short *ptr;
    *ptr = 0x11aa;
    c1 = *((char *)ptr);
    c2 = *((char *)ptr+1);
    printf("c1_address = %p,c1_value = 0x%x\n",(char *)ptr,(unsigned char)c1);
    printf("c2_address = %p,c2_value = 0x%x\n",(char *)ptr+1,c2);
    if((unsigned char)c1 == 0xaa)
        printf("Little_Endian\n");
    if((unsigned char)c1 == 0x11)
        printf("Big_Endian\n");
}

以上代码,在ubuntu10.04系统验证通过,X86架构处理器为小端模式;

上一篇下一篇

猜你喜欢

热点阅读