在c++中将int型数据打包成位域

Packing an int into a bitfield in C++

本文关键字:包成 位域 数据 c++ 中将 int      更新时间:2023-10-16

我正在将一些代码从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指针类型。只需将结构体的内存地址类型转换为数组的类型,并使用指针将值赋给该类型。