STM32字节对齐
STM32字节对齐
1. 字节对齐
字节对齐的含义:4字节对齐的含义就是变量地址对4求余数为0; 8字节对齐就是地址对8求余等于0
如:0x20000004,是四字节对齐,0x20000005不是四字节对齐;0x20000008是8字节对齐,0x20000009不是8字节对齐
2. STM32字节对齐
举例:
struct A
{
unsigned char a; //1 实际占用2字节
unsigned short int b; //2
unsigned int c; //4
unsigned long long d; //8
};
struct A a; //占用16字节
printf("%lld\n", (long long)sizeof(a));
输出结果为:16
STM32有方式取消字节对齐
#pargma pack(1)
#progma pack(1)
struct A
{
unsigned char a; //1 实际占用1字节
unsigned short int b; //2
unsigned int c; //4
unsigned long long d; //8
};
struct A a; //占用15字节
printf("%lld\n", (long long)sizeof(a));
输出结果为:15
3. STM32字节对齐的作用
STM32的字节对齐主要是为了提高访问速度,因为STM32的内存访问速度是8字节对齐的,如果变量不是8字节对齐,那么访问速度就会降低。