Search

10/15/2006

Union

  • a union is big enough to hold the wildest member.
  • a union is a structure in which all memebers have offset zero from the base.

利用union判斷是Big-endian or Litte-endian (from : C, A Reference Manual)
#include<stdio.h>
union{
long l;
char c[sizeof(long)];
}u;

int main(){
u.l = 1;
if(u.c[0] == 1)
printf("Addressing is right-to-left(Little-endian)\n");
else if (u.c[sizeof(long)-1] == 1)
printf("Addressing is left-to-right(Big-endian)\n");
else printf("Addressing is strangs\n");
}

32bit數0x12345678在litte-endian存放方式(假設從0x4000開始存放)
0x4000 0x78
0x4001 0x56
0x4002 0x34
0x4003 0x12

32bit數0x12345678在big-endian存放方式(假設從0x4000開始存放)
0x4000 0x12
0x4001 0x34
0x4002 0x56
0x4003 0x78

沒有留言: