在C ++中将int打包到一个位域中

时间:2011-07-30 06:05:05

标签: c++ bit-fields cpuid

我正在将一些代码从ASM转换为C ++,ASM看起来就像这样:

mov dword ptr miscStruct, eax

Struct看起来像:

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'

..我无法编辑结构

2 个答案:

答案 0 :(得分:1)

memcpy (&miscStruct, &CPUInfo[0], sizeof (struct miscStruct_s));

应该有帮助。

或只是

int *temp = &miscStruct;
*temp = CPUInfo[0];

这里我假设CPUInfo的类型是int。您需要使用temp数组的数据类型调整CPUInfo指针类型。只需将结构的内存地址类型转换为数组类型,然后使用指针将值分配到那里。

答案 1 :(得分:1)

汇编程序指令的字面翻译是这样的:

miscStruct=*(miscStruct_s *)&Info[0];

需要强制转型,因为C ++是一种类型安全的语言,而汇编程序则不是,但复制语义是相同的。

相关问题