c - 我可以有一点引用 C 位域的另一部分吗?
问题描述
我试图提出一个代码片段,其中结构的属性引用同一结构的另一个属性中的特定位。这看起来像:
struct A {
unsigned char type;
unsigned char is_family_a : 1; // should reference bit 7 of above somehow
};
struct A example;
example.type = 0x17;
printf("%i\n", example.is_family_a); // 0
example.type = 0xF7;
printf("%i\n", example.is_family_a); // 1
我查看了它的 cppreference 页面,但什么也没看到。我也环顾了stackoverflow,但并没有真正找到任何东西。如果我使用宏,这似乎确实有效,但我认为编译器可能会比我更好地优化这类事情。
解决方案
这应该这样做:
struct A {
union {
unsigned char type;
struct {
unsigned char : 7; // remove for big endian
unsigned char is_family_a : 1; // should reference bit 7 of above somehow
};
};
};
推荐阅读
- android - 单击保存按钮后,键/对值检索卡在“正在运行的活动”上
- php - PHP 邮件功能:我必须停用防火墙吗?
- c# - 撇号编码问题
- r - 使用 Lubridate 包从军用时间转换为标准时间,指示 AM/PM
- javascript - 铬 css/js 支持
- c# - C# 与 MySQL。从 MySQL 表中获取有关单元格、行及其值的信息
- tensorflow - 在 tf_trt create_inference_graph 上中止(核心转储)
- googletest - 如何告诉 gmock 忽略任何其他方法调用
- spring-security - Spring 依赖项未嵌入 HTTPSessionListener
- python - HTTPSConnectionPool SSL 错误证书验证失败