C语言 结构体、联合、位段
例如,有一些寄存器,寄存器有一些位,每个位都控制不同的设置,要是想单独设置某一个位的值,用位域就是一个比较好的方法,
位域可以无位域名,这时它只用来作填充或调整位置。无名的位域是不能使用的
比如
union _PWM_AUTO_Register{
long value;
struct {
uint16_t pwm_ofs_auto:8; // Automatically determined offset value
uint16_t :8;
uint16_t pwm_grad_auto:8; // Automatically determined gradient value
}PWM_AUTO_Register;
};
寄存器例子:
第一种方法:如果内存小的话可能造成堆栈溢出
union _GSTAT_Register { uint32_t value; struct GSTAT_Register *GSTAT_Register_bit; }; struct GSTAT_Register { uint8_t reset:1; // Indicates that the IC has been reset since the last read access to GSTAT uint8_t drv_err:1; // Indicates that the driver has been shut down due to overtemperature or short circuit detection since the last read access uint8_t uv_cp:1; // Indicates an undervoltage on the charge pump. The driver is disabled in this case. };
第二种方法:比第一种占用的更小
union _GSTAT_Register { uint32_t value; struct { uint8_t reset:1; // Indicates that the IC has been reset since the last read access to GSTAT uint8_t drv_err:1; // Indicates that the driver has been shut down due to overtemperature or short circuit detection since the last read access uint8_t uv_cp:1; // Indicates an undervoltage on the charge pump. The driver is disabled in this case. }GSTAT_Register; };
union _GSTAT_Register gstat = {0};//调用先出事化
gstat.GSTAT_Register.reset = 1;
gstat.GSTAT_Register.uv_cp =1;
sendData(GSTAT, gstat.value);
位段在使用中可能是从第零位开始0,1,2,3,4等,也可能是从最高位开始
union _DCCTRL_Register{ uint32_t value:24; struct { uint16_t dc_time:10, // Upper PWM on time limit for commutation :6, dc_sg:8; // Max. PWM on time for step loss detection using dcStep stallGuard2 in dcStep mode. }DCCTRL_Register; };
一串数字有6位是空的,可以忽略不写加上“:6”即为跳过6个字段,value总共占24位,可一位位操作
我这台是从零开始。
由于是一位一位操作所得到的数就是二进制数,不需要进制转换,与想传入的十进制数或者十六进制数一致。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理