大尾端小尾端

from:


big endian:大尾端,也称大端(高位)优先存储。

   little endian:小尾端,也称小端(低位)优先存储。

 

   如下00000000 00000000 00000000 00000001的存储

       

   大尾端: 00000000 00000000 00000000 00000001

           addr+0   addr+1    addr+2  addr+3    //先存高有效位(在低地址) 

  

   小尾端: 00000001 00000000 00000000 00000000

           addr+0   addr+1    addr+2  addr+3    //先存低有效位(在低地址)

 

   故要判断机器的体系结构是大尾端还是小尾端,以下程序可以完成任务:

  

   

 

 

#include <stdio.h>

int main()

{

    int tt = 1;

    char *c = (char*)(&tt);

    if(*c == 1)

    {

        printf("litte endian/n");

    }

    else

    {

        printf("big endian/n");

    }

    return 0;

}

 

 

 

大小尾端数据间的相互转换

 

#include <stdio.h>

typedef unsigned int u32;

typedef unsigned short u16;

#define BSWAP_16(x) /

        (u16) ( ((((u16)(x) & 0x00ff)) << 8) /

        | (((u16)(x) & 0xff00) >> 8) )

u16 bswap_16(u16 x)

{

    return ((x & 0x00ff) << 8) | ((x & 0xff00) >> 8);

}

u32 bswap_32(u32 x)

{

    return ((x & 0x000000ff) << 24) |

           ((x & 0x0000ff00) << 8) |

           ((x & 0x00ff0000) >> 8) |

           ((x & 0xff000000) >> 24);

}

int main()

{

    u16 num_16 = 0x1234;

    u32 num_32 = 0x12345678;

    printf("%x/n", bswap_16(num_16));

    printf("%x/n", BSWAP_16(num_16));

    printf("%x/n", bswap_32(num_32));

    return 0;

}

你可能感兴趣的:(c,存储,任务)