c++ - 在 C++ 中为 struct(union) 创建构造函数
问题描述
为结构(具有联合成员,有关系吗?)创建构造函数以将uint8_t
类型转换为结构的最佳方法是什么?
这是我的示例以澄清更多信息:
struct twoSixByte
{
union {
uint8_t fullByte;
struct
{
uint8_t twoPart : 2;
uint8_t sixPart : 6;
} bits;
};
};
uint32_t extractByte(twoSixByte mixedByte){
return mixedByte.bits.twoPart * mixedByte.bits.sixPart;
}
uint8_t tnum = 182;
print(extractByte(tnum)); // must print 2 * 54 = 108
PS 从评论和答案中查找,在 C++ 中无法对联合进行类型双关语。
给出的解决方案有点复杂,特别是在代码中有很多这些结构的地方。甚至在某些情况下,一个字节被分成多个位部分(两个以上)。因此,如果不利用联合,而是使用位集和移位位,则会给代码增加很多负担。
相反,我设法找到了一个更简单的解决方案。我只是在将类型传递给函数之前转换了它。这是固定代码:
struct twoSixByte
{
union {
uint8_t fullByte;
struct
{
uint8_t twoPart : 2;
uint8_t sixPart : 6;
} bits;
};
};
uint32_t extractByte(twoSixByte mixedByte){
return mixedByte.bits.twoPart * mixedByte.bits.sixPart;
}
uint8_t tnum = 182;
twoSixByte mixedType;
mixedType.fullByte = tnum;
print(extractByte(mixedByte)); // must print 2 * 54 = 108
解决方案
除非您迫切需要使用 a union
,否则不要使用它。将您的课程简化为:
struct twoSixByte
{
twoSixByte(uint8_t in) : twoPart((in & 0xC0) >> 6), sixPart(in & 0x3F) {}
uint8_t twoPart : 2;
uint8_t sixPart : 6;
};
如果需要获取完整字节,可以使用:
uint8_t fullByte(twoSixByte mixedByte)
{
return ((mixedByte.twoPart << 6) | mixedByte.sixPart);
}
推荐阅读
- php - 如何获取laravel项目中所有具有属性的表的名称
- php - JQUERY在文本函数上自动完成,该函数从html表单中的其他文本中获取输入
- google-api - 日历未与课堂链接
- ios - 我应该永远将 WKWebView 保留在 UICollectionView 中以避免重新加载吗?
- javascript - 是否可以在 Ajax 调用之前读取 Microsoft Excel 文件的内容?
- reactjs - 从 history.push 获取状态
- excel - EXCEL 高级匹配
- asp.net - .NET 路由不包括应用程序目录的完整路径?
- django - 仅对特定用户强制填写表单字段
- javascript - Angular JS 的下拉菜单中没有填充元素