在 C++ 中将 int 打包到位域中
我正在将一些代码从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
汇编指令的字面翻译是这样的:
需要强制转换,因为 C++ 是类型安全语言,而汇编程序不是,但复制语义是相同的。
The literal translation of the assembler instruction is this:
The casts are needed because C++ is a type-safe language, whereas assembler isn't, but the copying semantics are identical.
memcpy (&miscStruct, &CPUInfo[0], sizeof (struct MiscStruct_s));
应该有帮助。
或者简单地
在这里我假设
CPUInfo
的类型是int
。您需要使用CPUInfo
数组的数据类型来调整temp
指针类型。只需将结构的内存地址类型转换为数组的类型,然后使用指针将值分配到那里。memcpy (&miscStruct, &CPUInfo[0], sizeof (struct miscStruct_s));
should help.
or simply
Here i have assumed that the type of
CPUInfo
isint
. You need to adjust thetemp
pointer type with the datatype of theCPUInfo
array. Simply typecast the memory address for the structure to the type of the array and assign the value into there using the pointer.