不同的CPU,有大小端的问题(至少两个字节),也有比特序的问题。下面的例子运行在POWERPC和X86下运行的结果是不同的。这个在不同平台下,定义结构体要用到这个
例一:
#include "stdio.h"
#include "string.h"
struct entity_id
{
uint8_t instance: 7;
uint8_t logical: 1;
} __attribute__ ((packed));
int test_endian(void)
{
struct entity_id id;
uint8_t i = 0x96;
memcpy(&id, &i, sizeof(uint8_t));
printf("instance is %d/r/n",id.instance);
printf("logical is %d/r/n",id.logical);
return 1;
}
x86平台:
instance is 22
logical is 1
PPC平台:
instance is 75
logical is 0
例二、
#include "Stdio.h"
#include "Conio.h"
typedef unsigned short uint16_t;
struct _read
{
uint16_t settable:8;
uint16_t reserved:2;
uint16_t unr:1;
uint16_t ucr:1;
uint16_t unc:1;
uint16_t lnr:1;
uint16_t lcr:1;
uint16_t lnc:1;
};
void main(void)
{
struct _read read;
uint16_t n = 0x0036;
memcpy(&read,&n, 2);
printf("read.settable = 0x%x/r/n", read.settable);
printf("read.reserved = 0x%x/r/n", read.reserved);
printf("read.unr = 0x%x/r/n", read.unr);
printf("read.ucr = 0x%x/r/n", read.ucr);
printf("read.unc = 0x%x/r/n", read.unc);
printf("read.lnr = 0x%x/r/n", read.lnr);
printf("read.lcr = 0x%x/r/n", read.lcr);
printf("read.lnc = 0x%x/r/n", read.lnc);
getch();
}
这个程序运行在X86下,运行的结果是:
read.settable = 36
read.reserved = 0
read.unr = 0
read.ucr = 0
read.unc = 0
read.lnr = 0
read.lcr = 0
read.lnc = 0
这个程序运行在PPC下,运行的结果是:
read.settable = 0x0
read.reserved = 0x0
read.unr = 0x1
read.ucr = 0x1
read.unc = 0x0
read.lnr = 0x1
read.lcr = 0x1
read.lnc = 0x0
经验就留给大家去总结吧