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

发布于 2024-11-27 08:05:56 字数 806 浏览 4 评论 0原文

我正在将一些代码从 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'

..而且我无法编辑结构

I'm converting some code from ASM to C++, the ASM simply looks like so:

mov dword ptr miscStruct, eax

the Struct looks like:

struct miscStruct_s {
  uLong brandID     : 8,
  chunks            : 8,
  //etc
} miscStruct;

Is there an easy one-two line way to fill the struct in C++?
So far I am using:

miscStruct.brandID = Info[0] & 0xff; //Info[0] has the same data as eax in the ASM sample.
miscStruct.chunks = ((Info[0] >> 8) & 0xff);

That works fine and all, but I have to fill some 9-10 of these bitfield structs, some of them have 30 odd fields. So doing it this way ends up turning 10 lines of code into 100+ which obviously is not so great.

So is there a simple, clean way of replicating the ASM in C++?

I of course tried "miscStruct = CPUInfo[0];" but C++ doesn't like that unfortunately. :(

error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int'

..And I can't edit the struct.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

溺渁∝ 2024-12-04 08:05:56

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

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

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

The literal translation of the assembler instruction is this:

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

The casts are needed because C++ is a type-safe language, whereas assembler isn't, but the copying semantics are identical.

你又不是我 2024-12-04 08:05:56

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

应该有帮助。

或者简单地

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

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

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

should help.

or simply

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

Here i have assumed that the type of CPUInfo is int . You need to adjust the temp pointer type with the datatype of the CPUInfo array. Simply typecast the memory address for the structure to the type of the array and assign the value into there using the pointer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文