我使用的平台是小端模式:
声明这样一个联合体:
[mw_shl_code=c,true]typedef union
{
u32 dword;
u16 word[2];
u8 byte[4];
}u32val;[/mw_shl_code]
[mw_shl_code=c,true]int main()
{
u8 volatile a,b,c,d;
u16 volatile e,f;
u32val volatile u32j,*u32p;
u32 volatile g,h,i,j,k;
u32p = &u32j;
u32p->dword = 0x12345678;
a = u32p->byte[0];
b = u32p->byte[1];
c = u32p->byte[2];
d = u32p->byte[3];
e = u32p->word[0];
f = u32p->word[1];
g = (u32)u32p;
h = (u32)(u32p->byte);
i = (u32)(u32p->word);
j = (u32)&(u32p->byte[1]);
k = (u32)&(u32p->word[1]);
}
[/mw_shl_code]
可以省去移位操作,来进行字节拼接成字。
比如:地址的拼接与拆分。
例如这样一个函数:
[mw_shl_code=c,true]typedef union
{
u32 DWord;
u16 Word[2];
u8 Byte[4];
}UINT32_VAL;
u32 SPIReadDWord(u16 Address)
{
UINT32_VAL dwResult;
UINT16_VAL wAddr;
wAddr.Word = Address;
SPI_SEL_ENABLE;
SPI2_ReadWriteByte(CMD_SERIAL_READ);
SPI2_ReadWriteByte(wAddr.Byte[0]);
SPI2_ReadWriteByte(wAddr.Byte[1]);
dwResult.Byte[0] = SPI2_ReadWriteByte(0xff);
dwResult.Byte[1] = SPI2_ReadWriteByte(0xff);
dwResult.Byte[2] = SPI2_ReadWriteByte(0xff);
dwResult.Byte[3] = SPI2_ReadWriteByte(0xff);
SPI_SEL_DISABLE;
return dwResult.DWord;
}
[/mw_shl_code]
好处不言而喻。但是缺点就是,注意处理器的大小端模式。
一周热门 更多>