以下做单片机共用体字节对齐使用说明:
1、字节对齐代码:
#pragma pack (N) /*指定按N字节对齐*/
#pragma pack () /*取消指定对齐,恢复缺省对齐*/
2、应用示例:
#pragma pack (1) /*指定按 1 字节对齐*/
typedef union
{
struct
{
uint8_t data0;
uint8_t data1;
uint8_t data2;
uint8_t data3;
uint8_t data4;
}bits;
uint8_t buff[5];
}TEST_DAT;
#pragma pack () /*取消指定对齐,恢复缺省对齐*/
3、共用体均为 uint8_t 类型说明:
//共用体定义
#pragma pack (1) /*指定按 1 字节对齐*/
typedef union
{
struct
{
uint8_t data0;
uint8_t data1;
uint8_t data2;
uint8_t data3;
uint8_t data4;
}bits;
uint8_t buff[5];
}TEST_DAT;
#pragma pack () /*取消指定对齐,恢复缺省对齐*/
//共用体声明
TEST_DAT test_data;
//主函数功能
void main()
{
....
for(count =0; count < 5; count++) //赋值
{
test_data.buff[count] = count +1;
}
for(count =0; count < 5; count++) //
{
Debug_Printf(DEBUG_UART, "\r\n test_data.buff[%d] = %X ", count, test_data.buff[count]);
}
....
}
4、共用体均为 uint16_t 类型说明:内部数据反向
//共用体定义
#pragma pack (1) /*指定按 1 字节对齐*/
typedef union
{
struct
{
uint16_t data0;
uint16_t data1;
uint16_t data2;
uint16_t data3;
uint16_t data4;
}bits;
uint8_t buff[10];
}TEST_DAT;
#pragma pack () /*取消指定对齐,恢复缺省对齐*/
//共用体声明
TEST_DAT test_data;
//主函数功能
void main()
{
....
for(count =0; count < 10; count++) //赋值
{
test_data.buff[count] = count +1;
}
for(count =0; count < 10; count++) //
{
Debug_Printf(DEBUG_UART, "\r\n test_data.buff[%d] = %X ", count, test_data.buff[count]);
}
....
}