在c++中将int型数据打包成位域
Packing an int into a bitfield in C++
我正在将一些代码从ASM转换为c++, ASM简单地看起来像这样:
mov dword ptr miscStruct, eax
结构看起来像:
struct miscStruct_s {
uLong brandID : 8,
chunks : 8,
//etc
} miscStruct;
是否有一个简单的一两行方式来填补结构在c++ ?目前我使用的是:
miscStruct.brandID = Info[0] & 0xff; //Info[0] has the same data as eax in the ASM sample.
miscStruct.chunks = ((Info[0] >> 8) & 0xff);
这很好,但我必须填充9-10个位域结构体,其中一些有30个奇域。因此,这样做的结果是将10行代码变成100多行,这显然不是很好。
那么,是否有一种简单、干净的方法可以在c++中复制ASM ?
我当然尝试了"miscStruct = CPUInfo[0];",但不幸的是c++不喜欢这样。(
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int'
. .我不能编辑结构体
汇编指令的直译是:
miscStruct=*(miscStruct_s *)&Info[0];
需要强制类型转换,因为c++是一种类型安全的语言,而汇编语言不是,但是复制语义是相同的。
memcpy (&miscStruct, &CPUInfo[0], sizeof (struct miscStruct_s));
应该帮助。
或简称
int *temp = &miscStruct;
*temp = CPUInfo[0];
这里我假设CPUInfo
的类型是int
。需要根据CPUInfo
数组的数据类型调整temp
指针类型。只需将结构体的内存地址类型转换为数组的类型,并使用指针将值赋给该类型。
相关文章:
- C++Union/Struct位域的实现和可移植性
- 具有位域的结构的 Constexpr 构造函数
- 如何解释 #if/#else 位域?(VC++菜鸟)
- 枚举位域和聚合初始化
- 在有符号基础类型枚举的位域上溢出
- 如何检查位域是否跨越所有位
- 访问位域联合是C++标准中常见的初始数据未定义行为
- 锈迹位域和枚举C++样式
- C/C++:uint8_t位域的行为不正确且不一致
- 如何将位域写入二进制文件
- 字节序和大小为 1 的位域
- 面向对象编程 - 位域私有结构的公共参考
- 使用位域的结构大小不正确
- 在 mingw 的 gcc-5.3 下具有混合位域和枚举递减的结构的意外大小
- 如何将位域成员的所有位设置为 1
- 带有 C++ 位域的匿名 typedef 的前向声明
- 通过套接字C++发送时,位域值会更改
- 有符号的 int 会中断较大位域的某些部分
- 位域.为什么没有输出
- 在c++中将int型数据打包成位域